The thing is that pattern matching is performed mostly at runtime and types are resolved at compile time. Because of type erasure case v: List[Boolean] => ???
is not better than case v: List[_] => ???
. In the line case v: List[Boolean] => ...
compiler doesn't know that T =:= Boolean
. Pattern matching can't return different types from different cases.
So you can either pattern match with type tags and casting
case class MyClass[T](values: List[T]) {
import reflect.runtime.universe.{TypeTag, typeOf}
def myFunc(implicit typeTag: TypeTag[T]): T = values match {
case v: List[Boolean] if typeOf[T] <:< typeOf[Boolean] => false.asInstanceOf[T]
case v: List[MyType] if typeOf[T] <:< typeOf[MyType] => MyType.defaultVal.asInstanceOf[T]
case _ => throw new Exception("unsupported type")
}
}
or do this more type-safely with a type class (or polymorphic function)
case class MyClass[T](values: List[T]) {
def myFunc(implicit myFuncInstance: MyFunc[T]): T = myFuncInstance(values)
}
trait MyFunc[T] {
def apply(values: List[T]): T
}
object MyFunc {
implicit val booleanMyFunc: MyFunc[Boolean] = new MyFunc[Boolean] {
override def apply(values: List[Boolean]): Boolean = false
}
implicit val myTypeMyFunc: MyFunc[MyType] = new MyFunc[MyType] {
override def apply(values: List[MyType]): MyType = MyType.defaultVal
}
}