You are trying to implement the concept of a partial function. In doing so, you need to know that you sacrifice type safety for agility. In a strongly typed language, you usually cannot do this without any obvious hack, for example. softening the rules for applying types or variances.
, Scala PartialFunction : , . ,
trait Animal
case class Dog() extends Animal
case class Cat() extends Animal
"" Dog => T Animal => T ( ):
val pf: PartialFunction[Animal, Unit] = {
case Dog() => println("dog")
}
:
pf(Cat())
, Scala Scala , - , .. -T +T. @uncheckedVariance:
trait Consumer[+T, +V] extends (T@uncheckedVariance โ V) {
def handle(command: T@uncheckedVariance): V
}
:
val lookup: Map[Class[_], Consumer[Animal]] = Map(
classOf[Dog] โ dogConsumer,
classOf[Cat] โ catConsumer
)
( ).