Skip to content

Instantly share code, notes, and snippets.

@AndrewReitz
Created March 28, 2019 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewReitz/ce6c0e1b673ba7c3679b8c0869b23522 to your computer and use it in GitHub Desktop.
Save AndrewReitz/ce6c0e1b673ba7c3679b8c0869b23522 to your computer and use it in GitHub Desktop.
Like lazy in kotlin but you can also have setters.
fun <T: Any> lazy(initializer: () -> T): LazySetter<T> = LazySetter(initializer)
class LazySetter<T: Any>(private val initializer: () -> T) {
private var _value: T? = null
var value: T
get() = _value ?: initializer()
set(value) { _value = value }
}
inline operator fun <reified T: Any> LazySetter<T>.setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
inline operator fun <reified T: Any> LazySetter<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment