scala / scala3

The Scala 3 compiler, also known as Dotty.
https://dotty.epfl.ch
Apache License 2.0
5.72k stars 1.04k forks source link

Intersection types are not always commutative #19376

Open rskfocus opened 6 months ago

rskfocus commented 6 months ago

Compiler version

3.4.0-RC1

Minimized code

sealed trait Tagged[T]
sealed trait Row[A]

def run[R, A](tagged: Tagged[R & Row[A]], a: A): Tagged[R] = new Tagged[R] {}

/*
order of rows in type annotation affect either y or z compilation;
if changed to Tagged[Row[String] & Row[Int]] y fails to compile while z is not
*/
val x: Tagged[Row[Int] & Row[String]] = new Tagged[Row[Int] & Row[String]] {}

val y = run(x, 1) // compiles OK
val z = run(x, "s") // error

Output

Found:    ("s" : String)
Required: Int

Expectation

I expect that order of types in an intersection type doesn't affect type inference.

nicolasstucki commented 6 months ago

This seems to be an issue with inference. There are the types that get inferred

val y: Tagged[Row[Int] & Row[String]] = run[Row[Int] & Row[String], Int](x, 1)
val z: <error unspecified error> = run[Row[Int] & Row[String], Int](x, "s")

Note that writing the type explicitly fixes the issue

val z = run[Row[Int] & Row[String], String](x, "s") // compiles

There does not seem to be any issue with commutativity.

odersky commented 6 months ago

I expect that order of types in an intersection type doesn't affect type inference.

That's nowhere claimed and is probably impossible to achieve given that our type inference is incomplete.

So, unless someone points out a specific point in Scala 3's type inference algorithm that can be improved, I don't see any actionables here.