A property delegates to another property
Starting with Kotlin 1.4, a property can delegate its getter and setter to another property. This delegation is available for both top-level and class attributes (members and extensions).
Attribute Delegate attributes need to use the :: qualifier, for example, this:: Delegate or MyClass:: Delegate.
class MyClass(var memberInt: Int.val anotherClassInstance: ClassWithDelegate) {
var delegatedToMember: Int by this::memberInt
var delegatedToTopLevel: Int by ::topLevelInt
val delegatedToAnotherClass: Int by anotherClassInstance::anotherClassInt
}
var MyClass.extDelegated: Int by ::topLevelInt
Copy the code
When you want to rename an attribute in a backward-compatible way: introduce a new attribute, annotate the old attribute with the @deprecated annotation, and delegate its implementation.
class MyClass {
var newName: Int = 0
@Deprecated("Use 'newName' instead", ReplaceWith("newName"))
var oldName: Int by this::newName
}
fun main(a) {
val myClass = MyClass()
// Notice: 'oldName: Int' is deprecated.
// Use 'newName' instead
myClass.oldName = 42
println(myClass.newName) / / 42
}
Copy the code
Store attributes in a map
class User(valmap: Map<String, Any? >) {val name: String by map
val age: Int by map
}
// The constructor also accepts a mapping
val user = User(mapOf(
"name" to "John Doe"."age" to 25
))
Copy the code
Commissioned by the local
Local variables can be declared as delegate properties.
fun example(computeFoo: () -> Foo) {
val memoizedFoo by lazy(computeFoo)
if (someCondition && memoizedFoo.isValid()) {
memoizedFoo.doSomething()
}
}
Copy the code