Skip to content

Unexpected widening of covariant literal types #8231

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

Closed
soronpo opened this issue Feb 6, 2020 · 3 comments
Closed

Unexpected widening of covariant literal types #8231

soronpo opened this issue Feb 6, 2020 · 3 comments

Comments

@soronpo
Copy link
Contributor

soronpo commented Feb 6, 2020

[EDIT] After discussion on gitter, I managed to simplify the example, and more convinced that careful planning should be taken before considering changing this behavior.
As discussed on the PR introducing literal type operations, there is a problem when attempting to use covariant literal types.
Adding a <: Singleton upper bound resolved this issue, but IMO it feels hacky.

minimized code

class Foo[+LW] {
  def + [RW](that : Foo[RW]) = that
}

val f1 = new Foo[1]
val f2 = new Foo[2]

val f3 = f1 + f2
val f3a : Foo[2] = f1 + f2 //works
val f3b : Foo[2] = f3 //Error: type mismatch;

Compilation output

Found:    (f3 : Foo[Int])
Required: Foo[(2 : Int)]

expectation

No error

@odersky
Copy link
Contributor

odersky commented Feb 8, 2020

I changed the label to "enhancement" since it is not clear yet that this is a bug. Widening of singleton types is a difficult balance to achieve; every move in one direction can have downsides.

@soronpo
Copy link
Contributor Author

soronpo commented Feb 8, 2020

FWIW, it's the RHS that gets widened in regular classes, and both sides in case of extension classes. This also occurs in Scala 2 when macros are used to do the same literal type operation (the singleton-ops library). I understand the potential problem of changing widening behavior, but this really looks like a bug at very specific conditions: covariance+literal-types+staging.

@smarter
Copy link
Member

smarter commented Feb 9, 2020

As I explained on gitter:

type inference always widens singleton types before instantiating type parameters unless it is constrained not to do so
in f3a it is constrained by the expected type
the behavior you want is something like "because I expecitly wrote down that 2 in a type position, I don't want it to be widened as it propagates through type variables"
it's something I'd like to try implementing at some point

So closing because this is not a bug (and not any different from how scala 2 behaves), but it's still on my mind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants