Delegates in Kotlin

Hi Everyone,

Today we gonna discuss delegates in kotlin.

The Delegation pattern has proven to be a good alternative to implementation inheritance, and kotlin supports it natively requiring zero boilerplate code.

Property delegates don’t have to implement any interface, but they have to provide a getValue() and setValue() function.

let’s see an example, that mention in Kotlin ref docs. going to define Delegate class with getValue and setValue function.

class Delegate {

    operator fun getValue(thisRef : Any?, property : KProperty<*>) : String
    {
        return "${thisRef?.javaClass?.name}, thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(thisRef : Any?, property : KProperty<*>,value : String)
    {
        println("$value has been assigned to '${property.name}' in ${thisRef?.javaClass?.name}.")
    }
}

now creating another class.

class Example {
     var p : String by Delegate()
}

call Example class

fun main(args : Array)
{
    var example = Example()
    println(example.p)
    example.p = "delegate world"
}
//output:

com.delegated.Example, thank you for delegating 'p' to me!
delegate world has been assigned to 'p' in com.delegated.Example.

kotlin provides few delegated properties build into the language – Lazy properties, Observable properties, and properties storing in the map.

Lazy Properties: lazy is a function that takes a lambda and returns and returns an instance of Lazy which can serve as a delegate.

let’s create an example class.

class Example {
     val lazyValue: String by lazy {
          println("computed!") 
          "Hello"
     }
}
fun main(args : Array)
{
    println(example.lazyValue)
}
//output:
computed!
Hello

Observable properties: Observable takes two arguments: the initial value and a handle for modifications. the handler gets called every time we assign the property. it has three parameters: a property being assigned to, the old value and the new one.

let’s create an example class

class Example {
     
     var name: String by Delegates.observable("") {
          prop, old, new ->
          println("$old -> $new")
     }
}
fun main(args : Array)
{
    var example = Example()

    example.name = "first"
    example.name = "second"
}
//output:
 -> first
first -> second

Properties storing in the map: One common use case is storing the values of properties in a map. This comes up often in applications like parsing JSON or doing other “dynamic” things. In this case, you can use the map instance itself as the delegate for a delegated property.

let’s create an example class.

class User(val map: Map<String, Any?>) {
    val name:String by map
    val age: Int by map
}
fun main(args : Array)
{
    var user = User(mapOf("name" to "Ritesh pathak", "age" to 23))
    println(user.name)
    println(user.age)
}
//output:
Ritesh pathak
27

Ref – Kotlin docs.

Hope you like this. Thanks for reading 🙂

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s