Skip to content

Instantly share code, notes, and snippets.

@s1monw1
Last active January 3, 2018 00:09
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 s1monw1/e140a9dc334c07a008bfcaff7cd5f033 to your computer and use it in GitHub Desktop.
Save s1monw1/e140a9dc334c07a008bfcaff7cd5f033 to your computer and use it in GitHub Desktop.
class LazyContextAware<out T>(private val initializer: (Any?) -> T) : ReadOnlyProperty<Any?, T> {
private object UNINITIALIZED_VALUE
private var prop: Any? = UNINITIALIZED_VALUE
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return if (prop == UNINITIALIZED_VALUE) {
synchronized(this) {
return if (prop == UNINITIALIZED_VALUE) {
//invoke the initializer block with thisRef
initializer(thisRef).also { prop = it }
} else {
prop as T
}
}
} else prop as T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment