Last active
November 26, 2017 20:50
-
-
Save roschlau/fd812c653d9caeb91d72820f10e8ae5c to your computer and use it in GitHub Desktop.
Lazy Delegate implementation for a mutable, but lazily initialized variable
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
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