Skip to content

Instantly share code, notes, and snippets.

@pabloogc
Created July 30, 2018 15:11
Show Gist options
  • Save pabloogc/4e79fca0da9225669dfd8fae248ebee4 to your computer and use it in GitHub Desktop.
Save pabloogc/4e79fca0da9225669dfd8fae248ebee4 to your computer and use it in GitHub Desktop.
import java.util.*
import kotlin.reflect.KProperty
class MutableFieldProperty<R, T : Any>(private val initializer: (R) -> T) {
private val map = WeakHashMap<R, T>()
operator fun getValue(thisRef: R, property: KProperty<*>): T =
map[thisRef] ?: setValue(thisRef, property, initializer(thisRef))
operator fun setValue(thisRef: R, property: KProperty<*>, value: T): T {
map[thisRef] = value
return value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment