Skip to content

Delegation: using Property Delegation in kotlin

Devrath edited this page Feb 28, 2024 · 1 revision

Code to override the getter

class MainActivity : ComponentActivity()
{

    private val obj by MyLazy {
        println("Hello world")
        3
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            DelegationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) { Text(text = "Hello") }
            }
        }
    }

    class MyLazy<out T: Any>(
        private val initialize: () -> T
    ) {
        private var value: T? = null

        operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
            return if(value == null) {
                value = initialize()
                value!!
            } else value!!
        }
    }

}
Clone this wiki locally