How kotlin delegation is useful?

Viewed 1988

I'm really confused about the kotlin delegation. Let me describe the regular polymorphism approach here which looks same like the kotlin delgation.

interface Base {
    fun print()
}
class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}
fun main(args: Array<String>) {
    val b : Base = BaseImpl(10)
    b.print() // prints 10
}

I can pass any implemented class of Base interface to b variable to call the method of specified class's object. Then what is the benefit of kotlin's delegation? Which is described here.

interface Base {
    fun print()
}
class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}
class Derived(b: Base) : Base by b // why extra line of code? 
                                   // if the above example works fine without it.
fun main(args: Array<String>) {
    val b = BaseImpl(10)
    Derived(b).print() // prints 10
}

I know this is the simple scenario where the both codes are working fine. There should be a benefit of delegation that's why kotlin introduced it. What is the difference? and how kotlin delegation can be useful? Please give me a working example to compare with polymorphism approach.

4 Answers

Following is the example :-

enter image description here

interface Mode{
val color:String
fun display()
 }

class DarkMode(override val color:String) : Mode{    
override fun display(){
    println("Dark Mode..."+color)
}
 }
class LightMode(override val color:String) : Mode {
override fun display() { 
    println("Light Mode..."+color) 
}
}

class MyCustomMode(val mode: Mode): Mode{
override val color:String = mode.color
override fun display() { 
    mode.display()
}
}

Now, the custom mode can reuse display() function of both modes DarkMode & LightMode

fun main() {
MyCustomMode(DarkMode("CUSTOM_DARK_GRAY")).display()
MyCustomMode(LightMode("CUSTOM_LIGHT_GRAY")).display()
}

 /* output:
 Dark Mode...CUSTOM_DARK_GRAY
 Light Mode...CUSTOM_LIGHT_GRAY
*/

Kotlin natively support delegation pattern. Kotlin provides by keyword to specify the delegate object which our custom mode will be delegating to. We can achieve the same result of the code above using by keyword.

class MyCustomMode(val mode: Mode): Mode by mode
fun main() {
MyCustomMode(DarkMode("CUSTOM_DARK_GRAY")).display()
MyCustomMode(LightMode("CUSTOM_LIGHT_GRAY")).display()
}

/* output:
Dark Mode...CUSTOM_DARK_GRAY
  Light Mode...CUSTOM_LIGHT_GRAY
 */
Related