Binded variable with variable binding pattern matching is not casted to pattern's type

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?


Define your extractor for A exclusively.

object A {
  def unapply(a: A): Option[Int] = Some(a.n)

With your approach, the compiler can’t infer anything from the extractor application other than Any - the Base inference comes from the method parameter type.


Thanks for your reply!

I fixed my code based on your advice, and it works in expect.