Thanks to @senia's comment, I found the method.
In this case, callbackList
and cache
can be private[this]
(instance private. which is invisible from other instance of the same class).
Then I made types in methods to be invariant.
class CallbackNode[+A](getter: => A) {
private[this] var cache: Option[A]
private[this] var callbackList: List[A => Unit]
MyGraph.register(this)
def onChange(callback: A => Unit) { ... }
def update() {
val v = getter
storeInCache(v)
dependants.foreach { n => n.notify() }
callbacks.foreach { c => c(v) }
}
...
}
Graph is still CallbackNode[Any]
as nodes.
MyGraph
is for internal use, so this Any
is not a large problem.
The idea from shapeless will solve this problem, too, if needed.