Skip to content

Instantly share code, notes, and snippets.

@roschlau
Last active November 26, 2017 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roschlau/fd812c653d9caeb91d72820f10e8ae5c to your computer and use it in GitHub Desktop.
Save roschlau/fd812c653d9caeb91d72820f10e8ae5c to your computer and use it in GitHub Desktop.
Lazy Delegate implementation for a mutable, but lazily initialized variable
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Property delegate to allow lazy initialization of a mutable variable.
*/
class MutableLazy<T>(val init: () -> T) : ReadWriteProperty<Any?, T> {
private var value: Optional<T> = Optional.None()
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
if(value is Optional.None) {
value = Optional.Some(init())
}
return value.get()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = Optional.Some(value)
}
}
sealed class Optional<out T> {
abstract fun get(): T
class Some<out T>(val value: T): Optional<T>() {
override fun get() = value
}
class None<out T>(): Optional<T>() {
override fun get(): T {
throw NoSuchElementException("Can't get object from Optional.None")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment