Search code examples
scalagenericstypespattern-matchingtype-members

Pattern Match on Case Objects with Type Members


Scala has a nice feature to infer type parameter inside the pattern match. It also checks pattern match exhaustiveness. For example:

sealed trait PField[T]

case object PField1 extends PField[String]

case object PField2 extends PField[Int]

def getValue[X](f: PField[X]): X = f match {
  case PField1 => "aaa"
  case PField2 => 123
}

Is it possible to achieve the same but using type members instead of type parameters?

sealed trait Field {
  type T
}

case object Field1 extends Field {
  type T = String
}

case object Field2 extends Field {
  type T = Int
}

Following solutions do not work (Tested in Scala 2.12.6):

//No exhaustiveness check
def getValue[X](f: Field {type T = X}): X = f match {
  case Field1 => "aaa"
  //    case Field2 => 123
}

//casting needed
def getValue2[X](f: Field {type T = X}): X = (f: Field) match {
  case Field1 => "aaa".asInstanceOf[X]
  case Field2 => 123.asInstanceOf[X]
}

type Generified[X] = Field {type T = X}

//No exhaustiveness check
def getValue3[X](f: Generified[X]): X = f match {
  case Field1 => "aaa"
  //    case Field2 => 123
}

Type parameter is really problematic in my case because I have many sub-hierarchies of Fields and each hierarchy have some type classes. I can't put all the needed dependencies inside case object's because they are exported in a thin JAR to clients.


Solution

  • This solution is a simplified version of solution posted by @Andrey Tyukin. He stated that

    it does not hold that a.T = b.T for any two values a, b of type Field3.

    It means that, to have exhaustive pattern match, type members must be ignored. So in order to have both exhaustiveness and type inference we need sealed hierarchy with type parameters.

    He suggested to create separate hierarchy of case classes and pattern match on them instead of on the main hierarchy. However in my case it can be simplified: I created new sealed trait with type parameter but the same case objects are used for pattern match ("unique guarantee" is held in the object itself). This is final solution:

    sealed trait Field {
      type T
      def ug: TField[T]
    }
    
    sealed trait TField[G] extends Field {
      type T = G
      def ug: TField[T] = this
    }
    
    case object Field1 extends TField[String]
    case object Field2 extends TField[Int]
    
    def getValue[X](f: Field {type T = X}): X = (f.ug: TField[X]) match {
      case Field1 => "abc"
      case Field2 => 123
    }
    

    Thanks to that I can use Field trait to define type classes without going into higher kinded types and switch into TField[G] for pattern match.