-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Upper bound makes compiler infer Nothing
#14218
Comments
It's always delicate to decide whether type inference should instantiate a type variable to the lower or upper bound of its constraint when it appears in an invariant position, we end up relying on heuristics which won't always do what you expect. If you can make your type parameter variant that will let the compiler know which direction is more specific: scala> class Z[-S <: String](v: S => Unit)
// defined class Z
scala> new Z((s: String) => ())
val res4: Z[String] = ... |
Thanks, that helped! Making the type parameter contravariant fixes the problem. The full example in my code base fails to cross-compile with Scala 2 now (it seems variance checks for private members changed in Scala 3), but I think I will be able to sort this out. I think what is confusing here is that the expected type |
I think in Scala 3 |
Yeah, the heuristic will try to pick what the user passed if it's more specific than the default bounds, I think it'd make sense to also do that if the user passed something that matches one of the bound, but it's hard for the compiler to distinguish that from the user not passing any constraint. |
Indeed, this seems to be the case. Thanks!
Okay, I see. I agree it would make sense to do that since the behavior is quite surprising if you are not aware of the details of how type inference works. But it sounds like this would require quite some change. |
Hi, for the following code, the type of
res0
is inferred asZ[String]
in Scala 3:If you add an upper bound to the
S
type variable, the type ofres1
is inferred asZ[Nothing]
:Tested with Scala 3.1.0 and 3.1.1-RC1. This is also different from Scala 2, where the type in both cases is
Z[String]
. I would expect the upper bound not to change type inference and the compiler to infer the more useful typeString
.The text was updated successfully, but these errors were encountered: