Consider the following snippet:
object Test extends App {
class X {
class Y
}
class Z(val x: X) {
val y: x.Y = new x.Y
}
val x: X = new X
val z: Z = new Z(x)
val y: x.Y = z.y
println(y)
}
This code won't compile, complaing about incompatible path-dependent types:
[error] 12 | val y: x.Y = z.y
[error] | ^^^
[error] | Found: (Test.z.y : Test.z.x.Y)
[error] | Required: Test.x².Y
[error] |
[error] | where: x is a value in class Z
[error] | x² is a value in object Test
[error] |
Is there a way to gently remind the compiler that z.x is assigned to x just one line above?
Even if (z.x == x) { val y: x.Y = z.y } does not solve the issue, even though path equivalence should be inferred from control flow.
Background: Scala 3 macro API heavily uses PDT's, and this creates huge amount of pain to deal with --- all this pain is coming from compiler's inability to infer anything, and lack of syntactic structures to explicitly control that inference.
This is correct behavior for path-dependent types (by the way, in Scala 2 it's the same).
Would you be satisfied with
?
z.xequalsxbut this doesn't mean that the typez.x.Yisx.Y.Similarly,
aequals toa1but this doesn't mean that the typea.Tisa1.T.This is Scala 2 spec for equivalence of path-dependent types: https://scala-lang.org/files/archive/spec/2.13/03-types.html#equivalence. In our case the prefixes have different singleton types:
You can fix the compilation:
and
See also:
In the latest release of scala (2.12.x), is the implementation of path-dependent type incomplete?
Cannot prove equivalence with a path dependent type
Force dependent types resolution for implicit calls
How to help the Scala 3 compiler infer a path-dependent-type?
How to create an instances for typeclass with dependent type using shapeless
If you use REPL you'll see the types inferred by the compiler (removing explicit type annotations as @LuisMiguelMejíaSuárez advised in comments):