Created
January 9, 2020 10:10
-
-
Save happy-bracket/ad961cb042491e9682a6305b82aae00a to your computer and use it in GitHub Desktop.
Chainable lateinit
This file contains hidden or 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 Lateinit<T> { | |
private var value: T? = null | |
private var dependants = mutableListOf<Dependant<T, *>>() | |
operator fun getValue(thisRef: Any?, kprop: KProperty<*>): T = | |
value ?: throw Exception() | |
operator fun setValue(thisRef: Any?, kprop: KProperty<*>, v: T) { | |
value = v | |
dependants.forEach { d -> | |
d.initialize(v) | |
} | |
} | |
fun depend(d: Dependant<T, *>) { | |
dependants.add(d) | |
} | |
} | |
class Dependant<A, T>(private val init: (A) -> T) { | |
private var value: T? = null | |
fun initialize(dep: A) { | |
value = init(dep) | |
} | |
} | |
fun <T> late(): Lateinit<T> = Lateinit() | |
fun <A, T> lateDependOn(a: Lateinit<A>, init: (A) -> T): Dependant<A, T> { | |
val d = Dependant(init) | |
a.depend(d) | |
return d | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment