Scala self types in pattern matching

530 Views Asked by At

Given that I can create a trait that has self types and restricts the implementation and gives access to members like this:

trait A { def a:String }
trait B { def b:String }

trait C {
   self: A with B =>
   lazy val c:String = a+b
}

Why can't I bring that concept into a pattern match. I know below does not work, but is it just missing some syntactic sugar or are there limitations that prevents this?

case class AB( a:String, b:String ) extends A with B
val ab = AB("a","b")

ab match {
  case ab@(A & B) => ab.a + ab.b
}

What does work are these less elegant versions

ab match {
  case a:A => a match {
    case b:B => a.a + b.b
  }
}

def checkInstanceOf(obj:AnyRef) = 
  obj.isInstanceOf[A] && obj.isInstanceOf[B]
ab match {
  case ab if(checkInstanceOf(ab)) => ab.a + ab.b
}

My goal is to be able to write generic type driven behavior based on two or more traits being implemented.

1

There are 1 best solutions below

2
On BEST ANSWER

A normal typecheck for type A with B works:

ab match {
  case ab: A with B => ab.a + ab.b
}