Skip to content

Type inference difficulties with UndefOr[A | B] #14770

Closed
@armanbilge

Description

@armanbilge

Compiler version

3.1.3-RC1-bin-20220323-fb7f900-NIGHTLY

Minimized code

UndefOr is based on the Scala.js concept:

https://github.com/scala-js/scala-js/blob/058532aa8c504b76431b40e3e1b51b2cdef87643/library/src/main/scala/scala/scalajs/js/package.scala#L85

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions