Generic constrained Map using higher-kinded-types?
I am trying to implement a result cache (Loader class) that maps hashable
instances of class Resolver[T] to Result instances, where T is has type of
Result. Of course a user is given the possibility to specialize the the
Result class providing extra methods that are application specific. The
point is that using the Loader.get method the user has also to specify the
resulting type:
val s = Loader.get(new
SpecializedResolver()).asInstanceOf[SpecializedResult]
What I want is to avoid the cast and make it implicit so the code should
be something like:
val implicitS = Loader.get(new SpecializedResolver())
The code I have at the moment is the following:
import scala.language.existentials
abstract class Result {
def computed: Boolean
}
abstract class Resolver[T <: Result] {
def result(): T forSome {type T <: Result}
}
class SpecializedResult extends Result {
def computed = true
def special() = 42
}
class SpecializedResolver extends Resolver[SpecializedResult] {
def result = new SpecializedResult
}
object Loader {
val cache = collection.mutable.Map[K forSome {type K <: Resolver[_]}, V
forSome {type V <: Result}]()
def get[K <: Resolver[_]](k: K): V forSome {type V <: Result} = {
cache.getOrElseUpdate(k, { k.result } )
}
}
object Runner {
def main(args: Array[String]) {
val s = Loader.get(new
SpecializedResolver()).asInstanceOf[SpecializedResult]
println("Value is: %d".format(s.special))
val implicitS = Loader.get(new SpecializedResolver())
// test.scala:34: error: value special is not a member of Result
println("Value is: %d".format(implicitS.special))
}
}
Since I am relatevely new to the scala language my question is: is it even
possible to achieve this implicit cast by using higher-kinded-types
feature that scala provides? I took a look at the talk 'High Wizardry in
the Land of Scala' where the speaker Daniel Spiewak introduces a
higher-order HOMap that does something similar but I still don't well
understand how to adapt his solution to my case.
No comments:
Post a Comment