Samar Samar - 3 months ago 25
Scala Question

Scala generic subtype parameters

Why does the compiler treat t1 ++ t2 result as List[Any]? Concatenating two Lists of type S should return a list of type S only.

// compiles
def cons[S <: List[Any]](t1: S, t2: S): S = t1

// type mismatch; found List[Any] required S
def cons[S <: List[Any]](t1: S, t2: S): S = t1 ++ t2

Answer

After [S <: List[Any]] every S has to obey the same rules/laws, but they don't have to be the same.

scala> def cons[S <: List[Any]](t1: S, t2: S): S = t1 
cons: [S <: List[Any]](t1: S, t2: S)S

scala> cons(List('c','b'),List(2,3))
res15: List[AnyVal] = List(c, b)

Your cons will work if you let the compiler determine the result type (which will always be Any).

scala> def cons[S <: List[Any]](t1: S, t2: S) = t1 ++ t2
cons: [S <: List[Any]](t1: S, t2: S)List[Any]

scala> cons(List(2,3), List(5,6,9))
res19: List[Any] = List(2, 3, 5, 6, 9)