Delegating to another property

2 0 0
                                        

Delegating to another property means that a property can use other variable's getters and setters to be its representative. The representative can be from the following: 

1. a top level

    syntax:

    var topLevelProp1: String = "Value"

    class NameA{

        var message: String by ::topLevelProp1

    }

2. a class property member

    syntax:

    class NameA{

        var prop1: String = "Value"

        var message: String by this::prop1

    }

3. an extension property either of the same class

    syntax:

     var topLevelProp1: String = "Value"

    class NameA{

     }

     var NameA.message : String by ::topLevelProp1

     fun main(){}

4. coming from an object defined in a parameter.

    syntax:

    class NameA{

        var prop1: String = "Value"

    }

    class NameB{

        fun methodName(objA: NameA){

            var message: String by objA::prop1

        }

    }


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

fun main(){

    val fc = FirstClass()

    println(fc.doSomething(SecondClass()))

}

class FirstClass{

    fun doSomething(obj1: SecondClass): String{

        var message: String by obj1::prop1

        return message

    }

}

class SecondClass{

    var prop1: String = "Hello World"

}

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

Result: 

Hello World


Kotlin ProgrammingWhere stories live. Discover now