Last active
January 3, 2018 00:09
-
-
Save s1monw1/e140a9dc334c07a008bfcaff7cd5f033 to your computer and use it in GitHub Desktop.
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
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