class Example {
var p: String by Delegate()
}
class Delegate {
operator fun getValue(refr: Any?, prop: KProperty<*>): String {
return "Thank you for delegating '${property.name}' to me!"
}
operator fun setValue(refr: Any?, prop: KProperty<*>, v: String) {
println("$v assigned to '${property.name}'")
}
}
val ex = Example()
ex.p = "NEW" // prints "NEW assigned to ‘p’".
val lazyValue: String by lazy {
"Hello"
}
var counter: Int by Delegates.observable(0) { prop, old, new ->
println("$old -> $new")
}
var username: String by Delegates.vetoable("None") { prop, old, new ->
new.isNotEmpty()
}
val frameLayout: FrameLayout by bindView(R.id.frameLayout)
var rememberPin: Boolean by Cacheable("rememberPin", false)
var companyColor: Int by Cacheable("companyColor", Color.BLACK) {
Bus.post(UpdateColorMessage())
}
class User(val map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}