Skip to content

Instantly share code, notes, and snippets.

@felipecsl
Created October 22, 2017 23:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save felipecsl/46f69942d57a9381dea60d4f361458a4 to your computer and use it in GitHub Desktop.
Save felipecsl/46f69942d57a9381dea60d4f361458a4 to your computer and use it in GitHub Desktop.
A Kotlin lazy that can be set to override the initializer value
private fun <T> mutableLazy(initializer: () -> T) = Delegate(lazy(initializer))
class Delegate<T>(private val lazy: Lazy<T>) {
private var value: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: lazy.getValue(thisRef, property)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
@felipecsl
Copy link
Author

Use it like

var foo: String by mutableLazy { "bar" }

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