Search code examples
scala

Infer type member through pattern matching in Scala


Is there a way to make it work? I.e. to tell the compile that within a patmat case the e has more specific type and so the static value of Param?

sealed trait MyEnum {
 type Param
}

object MyEnum {
  case object Value1 extends MyEnum {
    type Param = Int
  }
}

trait MyTypeClass[T]

val i: MyTypeClass[Int] = null

def get(e: MyEnum): MyTypeClass[e.Param] = e match {
    case MyEnum.Value1 => i
}

Currently the compiler fails with

type mismatch;
 found   : Playground.MyTypeClass[Int]
 required: Playground.MyTypeClass[e.Param]

Im working with scala 2.13.x


Solution

  • I think you can use a type parameter for the get method instead of directly matching e.Param. Modify the method like this:

    def get[T](e: MyEnum { type Param = T }): MyTypeClass[T] = e match {
        case MyEnum.Value1 => i.asInstanceOf[MyTypeClass[T]]
    }
    

    This way, the compiler knows that within each case, e.Param is specific.