Created
August 11, 2016 05:20
-
-
Save kittinunf/bc6a29a7b0931c66334a3bb3cfd68090 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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