Local Delegated Properties

5 0 0
                                        

Local Delegated Properties - Local because it is within the function block or body. Delegated because the variable that you are going to use is using a delegation.

==================

fun main(){

    val obj = PracticeLocalDelegatedProperties(10.0, 10.0)

    obj.doSomething("any"){obj.calculateThePerimeter()}

    obj.doSomething("area") { obj.calculateTheArea() }

    obj.doSomething("perimeter"){obj.calculateThePerimeter()}

}

class PracticeLocalDelegatedProperties(private val length: Double, private val width: Double) {

    fun doSomething(calculateMessage: String, here: () -> Double){

        val local1: Double by lazy(here)

        when(calculateMessage){

            "area" -> println("Area: $local1")

            "perimeter" -> println("Perimeter: $local1")

             else -> println("Choose \'area\' or \'perimeter\' only")

        }

    }

    fun calculateTheArea(): Double{

        return length * width

    }

    fun calculateThePerimeter(): Double{

        return 2.0 * (length + width)

    }

}

==================

Result:

Choose 'area' or 'perimeter' only

Area: 100.0

Perimeter: 40.0


Note: The variable named local1 inside the function used a lazy delegation to get its value. It gets the value from a lambda function named here

Kotlin ProgrammingWhere stories live. Discover now