Search code examples
scaladesign-patternstypes

Scala: Using supertype operator in pattern matching


I have made my own framework of traits and classes that extend my traits. The parent of all classes is a trait named 'Contract'. 'Combinator' and 'ElementaryContract' are two immediate children of Contract.

def disintegrateContract[T](element: T): Elem = 
{

    element match
    {
      case com <: Combinator =>  matchCombinator(com)
      case e <:ElementaryContract =>matchElementaryContract(e)
    }
}

I want to make a match class that recognizes whether a passed 'Contract' is a subtype of 'Combinator' or 'ElementaryContract' and then pass it to some other functions. This is the compilation error I get:

 '=>' expected but '<:' found

Probably it does not recognize the subtype operator. How can I make this happen?


Solution

  • If understood you correctly the usual pattern matching should be fine -- if Bar extends Foo, it is Foo (plus something else):

    class SuperA
    class ImplA extends SuperA
    
    class SuperB
    class ImplB extends SuperB
    
    def disintegrateContract[T](element: T) = element match {
       case a: SuperA =>  println("I extend SuperA")
       case b: SuperB =>  println("I extend SuperB")
    }
    
    disintegrateContract(new ImplA)
    // I extend SuperA
    disintegrateContract(new ImplB)
    // I extend SuperB
    

    To have exact your situation there should be Super which SuperA and SuperB will extend, but it changes nothing.