Hi,
I implemented unapply
method in companion object and used it in pattern matching.
However, in the variabile binding pattern maching, it does not cast a variable into pattern’s type.
For example, pattern match in below code does not cast a
into A
and causes an compile error in 2.12.11 and 2.13.1 interpreter .
trait Base
class A(val n: Int) extends Base
class B(val s: String) extends Base
object A {
def unapply(obj: Any): Option[Int] = obj match {
case a: A => Some(a.n)
case _ => None
}
}
def f(base: Base): Unit = base match {
case a @ A(_) => println(a.n) // compile error! value n is not a member of Base
case _ =>
}
However, If I use case class, it is casted in expect.
I think there is what I missed, so please tell me how to do that?
Thanks.