private var value: T? = null
4
5
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
6
return value ?: throw IllegalStateException("${desc.name} " +
7
"not initialized")
8
}
9
10
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
11
this.value = if (this.value == null) value
12
else throw IllegalStateException("${desc.name} already initialized")
13
}
14
}
Now let’s create an object with a function that provides your new delegate:
1
object DelegatesExt {
2
fun notNullSingleValue():
3
ReadWriteProperty = NotNullSingleValueVar()
4
}
16.5 Reimplementing App Singleton
Delegates can help us in this situation. We know that our singleton is not going to be null, but we
can’t use the constructor to assign the property. So we can make use of a
lateinit
delegate:
1
class App : Application() {
2
3
companion object {
4
lateinit var instance: App
5
}
6
7
override fun onCreate() {
8
super.onCreate()
9
instance = this
10
}
11
}
The problem with this solution is that we could change the value of this instance from anywhere
in the App, because a
var
property is required if we want to use
lateinit
. That’s easy to solve by
using a private
set
:
16 Application Singleton and Delegated Properties
63
1
companion object {
2
lateinit var instance: App
3
private set
4
}
But we’ll be making use of our custom delegate instead:
1
companion object {
2
var instance: App by DelegatesExt.notNullSingleValue()
3
}
Though, in this case,
lateinit
is probably the most simple option, I wanted to show you how to
create a custom property delegate and use it in your code.
Do'stlaringiz bilan baham: |