Skip to content

Instantly share code, notes, and snippets.

@kittinunf
Created August 11, 2016 05:20
Show Gist options
  • Save kittinunf/bc6a29a7b0931c66334a3bb3cfd68090 to your computer and use it in GitHub Desktop.
Save kittinunf/bc6a29a7b0931c66334a3bb3cfd68090 to your computer and use it in GitHub Desktop.
interface SingleAssignType<T> {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T)
}
class SingleAssign<T> : SingleAssignType<T> {
private var initialized = false
private var _value: Any? = null
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (!initialized)
throw Exception("Value has not been assigned yet!")
@Suppress("UNCHECKED_CAST")
return _value as T
}
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
if (initialized) {
throw Exception("Value has already been assigned!")
}
_value = value
initialized = true
}
}
//usage
class Bar {
var f: Foo by SingleAssign()
fun doSomething() {
f = createFoo()
f.foo() //use normally and foo is not nullable type
f = createAnotherFoo() //throw exception as f has been initialized
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment