16 Application Singleton and Delegated Properties
61
1
val conf = Configuration(mapOf(
2
"width" to 1080,
3
"height" to 720,
4
"dp" to 240,
5
"deviceName" to "mydevice"
6
))
16.4 How to create a custom delegate
Let’s say we want, for instance, to create a non-nullable delegate that can be only assigned once.
Second time it’s assigned, it will throw an exception.
Kotlin library provides a couple of interfaces our delegates must implement:
ReadOnlyProperty
and
ReadWriteProperty
. The one that should be used depends on whether the delegated property is
val
or
var
.
The first thing we can do is to create a class that extends
ReadWriteProperty
:
1
private class NotNullSingleValueVar
() : ReadWriteProperty {
2
3
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
4
throw UnsupportedOperationException()
5
}
6
7
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
8
9
}
10
}
This delegate can work over any non-nullable type. It will receive a reference of an object of any
type, and use
T
as the type of the getter and the setter. Now we need to implement the methods.
• The getter will return a value if it’s assigned, otherwise it will throw an exception.
• The setter will assign the value if it is still null, otherwise it will throw an exception.
16 Application Singleton and Delegated Properties
62
1
private class NotNullSingleValueVar
() : ReadWriteProperty {
2
3
Do'stlaringiz bilan baham: