'Generic type matching at runtime scala 3
I want to a list function (implemented through generic), they share the same function name but different parameter types. For a given parameter variable, is it possible to pick the "suitable" function from the list to call it?
Also is it possible to match type in a trait in scala 3? Like the code below.
I wonder if it possible to achieve this without reflection, e.g. TypeTag.
trait Target
trait TargetBuilding extends Target
trait TargetUnit extends Target
trait Do[T <: Target] {
type targetType = T
def hit(x: T): Unit
}
val x1 = new Do[TargetBuilding] {
override def hit(x: TargetBuilding): Unit = println("hit " + x.toString)
}
val x2 = new Do[TargetUnit] {
override def hit(x: TargetUnit): Unit = println("Eat " + x.toString)
}
val q: Seq[Do[_ >: TargetBuilding & TargetUnit <: Target]] = x1 :: x2 :: Nil
//val q: Seq[Do[_ >: TargetBuilding & TargetUnit <: Target]] = x2 :: x1 :: Nil
val data = new TargetBuilding {
override def toString: _root_.java.lang.String = "a building"
}
q foreach { x =>
type tt = x.targetType
data match {
case y: tt => x.hit(y)
case _ =>
}
}
If Target is assumed to be sealed, is there any difference?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
