Underscores in type bounds on type constructors
Asked Answered
M

1

7

Can someone explain why the following doesn't compile? I want that BB[A] is also a List[A]. The method body only enforces this view.

scala> def x[A, BB[_] <: List[_]](p: BB[A]) {p: List[A]}
<console>:8: error: type mismatch;
 found   : BB[A]
 required: List[A]

       def x[A, BB[_] <: List[_]](p: BB[A]) {p: List[A]}
                                             ^
Marthmartha answered 27/6, 2011 at 12:36 Comment(1)
Is there a reason you use the variable name p two times? First as a BB[A] and then as List[A]? Or am I missing something obvious?Janey
L
10

I think you need to name the _ parameter.

scala> def x[A, BB[X] <: List[X]](p: BB[A]) {p: List[A]}

works.

Laurasia answered 27/6, 2011 at 12:51 Comment(3)
indeed, the definition BB[_] <: List[_] means something else: BB[x] <: List[T forSome {type T}], the _ only defines an anonymous higher-order type parameter when defining a type parameter list. In all other positions, _ introduces an anonymous existential type (like a Java wildcard). Thus, in List[_], where the _ is used as a type argument (it's not defining a new type parameter list for List of course), it becomes an existential type. Think of it another way: if you had multiple anonymous type parameters (which are all called _, how would you refer to them individually?)Shavers
I find it helps readability to use a lowercase "name" for type placeholders like this. Wouldn't go so far as to call it idiomatic, but it's certainly a trend I've seen used by others.Mayda
Also, comparing the level of types and values, it is quite unfortunate that the type-level underscore behaves differently from the value-level underscore. At the value level, _ + _ indeed stands for (x, y) => x + y, a function. As hinted at in my other comment, the type-level underscore is context-sensitive, and it never introduces a type-level function. It's either an anonymous type parameter definition or an anonymous existential. Neither of these have value-level equivalents.Shavers

© 2022 - 2024 — McMap. All rights reserved.