Created
December 22, 2015 03:13
-
-
Save motorro/e650bfb3942728226bb5 to your computer and use it in GitHub Desktop.
Lazy delegate with respect to context
This file contains 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
object Delegates { | |
/** | |
* Lazy read-only property with respect to calling context in initializer | |
* @param initializer Lazy initializer | |
*/ | |
public fun <T> contextLazy(initializer: Any?.() -> T): ReadOnlyProperty<Any?, T> = UnsafeContextLazy(initializer) | |
} | |
/** | |
* Lazy read-only property with respect to calling context in initializer | |
* @param initializer Lazy initializer | |
* Not thread-safe! | |
*/ | |
private class UnsafeContextLazy<out T>(private val initializer: Any?.() -> T) : ReadOnlyProperty<Any?, T> { | |
private var value: T? = null | |
override fun getValue(thisRef: Any?, property: KProperty<*>): T { | |
if (null == value) { | |
value = thisRef.initializer() | |
} | |
return value ?: throw IllegalStateException("Property ${property.name} failed to initialize with initializer.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that would be a good idea to copy-and-modify the code from stdlib: http://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/util/Lazy.kt#L37
It is very cleaver, for example it does not produce memory leaks.