Skip to content

Instantly share code, notes, and snippets.

@motorro
Created December 22, 2015 03:13
Show Gist options
  • Save motorro/e650bfb3942728226bb5 to your computer and use it in GitHub Desktop.
Save motorro/e650bfb3942728226bb5 to your computer and use it in GitHub Desktop.
Lazy delegate with respect to context
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.")
}
}
@voddan
Copy link

voddan commented Dec 22, 2015

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.

@voddan
Copy link

voddan commented Dec 22, 2015

Currently you code should not compile. Try to run it at http://try.kotlinlang.org/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment