DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Updated on • Originally published at sanjayprajapat.hashnode.dev

Standard Delegates In Kotlin

1. lazy property - it used to create an object that is initialized only first access to the property value and store value and return it. By default lazy is synchronized the value is computed only in one thread ,and value will be same in all thread

/* immutable variable*/
val ourValue:String by lazy(){
    println("Hello World") 
    callAnother() /* this will run only first access*/
    "Hello what is going on "
}

 fun callAnother(){
    print("another fun ")
}
Enter fullscreen mode Exit fullscreen mode
 fun main(args: Array<String>) {
     println(ourValue) 
     println(ourValue)
     println(ourValue)
    //  ourValue = 90 // value can't change

}
/* 
output 
Hello World
another fun 
Hello what is going on
Hello what is going on
Hello what is going on
*/
Enter fullscreen mode Exit fullscreen mode

2. Observable Properties: lambda will be triggerd every time when value of property will be changed.

import kotlin.properties.Delegates
class Person{
    /* mutable variable  */
    var ourValue: String by Delegates.observable("Hello World"){ property ,oldValue,newValue ->
         print("\n prop $property ")
         print("\n oldValue $oldValue ") 
         print("\n newValue $newValue ")
    }
}
Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {
    val p = Person()
    print(p.ourValue)  // Hello World 
    p.ourValue = "change world"

}

// output
// Hello World
//  prop property ourValue (Kotlin reflection is not available)
//  oldValue Hello World
//  newValue change world
Enter fullscreen mode Exit fullscreen mode

3. vetoable - it 's simmilar to obervable , only change is when assign the value onChange (callback)
is called if return true then new value will be assigned otherwise old value.

class Person1{
    var ourValue by Delegates.vetoable("Hello") {
        property, oldValue, newValue -> 
        newValue.length > oldValue.length  /* condition should be true to assign new value */
    }
}
Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {
    val p1 = Person1()
    p1.ourValue = "World"  // Hello
    p1.ourValue = "Worlds"
    println(p1.ourValue) // Worlds 


}
Enter fullscreen mode Exit fullscreen mode

4. notNull - this delegates is used to be initialized later. it's similar to lateinit. It can be used with primitive data type which lateinit not support

var fullname: String by Delegates.notNull<String>()

fun main(args: Array<String>) {
    // can't access without initialization , gives exception 
    print(fullname) //  java.lang.IllegalStateException
    fullname = "Justin Bieber"
    print(fullname) // Justin Bieber
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)