Scala type overlay violates type compatibility

I have always believed that type aliases always expand to their original type, if necessary. But, here is a troublemaker

def a[P](a: Option[P]) = { type Res = List[P] // result type alias Nil: Res // Replace this line with Nil: List[P] to clear the error } def b[V](v: V) = a(Some(v)): List[V] 

crash ( scastie )

 error: type mismatch; found : Res (which expands to) List[P] required: List[V] 

You see that a converts Option[P] => List[P] and since b supplies Some[V] , a converts Option[V] => List[V] when b calls it. But the compiler says the result is incompatible with List[V] . How is this possible? The error will disappear ( scastie ) if you replace Nil: Res with Nil: List[P] in a . You need to eliminate the type alias in order to get rid of the error. This means that the type alias is the culprit.

+5
source share
1 answer

I am pretty sure this is a compiler error. Type aliases are assumed to automatically expand in Scala, in which case type a is output as [P](Option[P]) => Res instead of [P](Option[P]) => List[P] . And since Res is in the inner area, the compiler cannot find it for the correct input of type b .

0
source

All Articles