Closed
Description
Compiler version
3.1.3-RC1-bin-20220323-fb7f900-NIGHTLY
Minimized code
UndefOr
is based on the Scala.js concept:
The minimized example below demonstrates a common situation when working with Scala.js facades.
//> using scala "3.1.3-RC1-bin-20220323-fb7f900-NIGHTLY"
type UndefOr[A] = A | Unit
extension [A](maybe: UndefOr[A])
def foreach(f: A => Unit): Unit =
maybe match
case () => ()
case a: A => f(a)
trait Foo
trait Bar
object Baz:
var booBap: Foo | Bar = _
def z: UndefOr[Foo | Bar] = ???
@main
def main =
z.foreach(x => Baz.booBap = x)
Output
$ scala-cli compile test.scala
Compiling project (Scala 3.1.3-RC1-bin-20220323-fb7f900-NIGHTLY, JVM)
[error] ./test.scala:21:31: Found: (x : Object)
[error] Required: Foo | Bar
[error] z.foreach(x => Baz.booBap = x)
[error] ^
Error compiling project (Scala 3.1.3-RC1-bin-20220323-fb7f900-NIGHTLY, JVM)
Compilation failed
Expectation
If we add an explicit type annotation to the last line:
- z.foreach(x => Baz.booBap = x)
+ z.foreach((x: Foo | Bar) => Baz.booBap = x)
then it compiles ok:
$ scala-cli compile test.scala
Compiling project (Scala 3.1.3-RC1-bin-20220323-fb7f900-NIGHTLY, JVM)
[warn] ./test.scala:9:12: the type test for A cannot be checked at runtime
[warn] case a: A => f(a)
[warn] ^
Compiled project (Scala 3.1.3-RC1-bin-20220323-fb7f900-NIGHTLY, JVM)
Is it possible for the compiler to make this inference by itself?