Skip to content

Flow typing leads to incorrect "pattern type is incompatible with expected type" error #18083

Closed
@smarter

Description

@smarter

Compiler version

3.3.1-RC1 with -Yexplicit-nulls

Minimized code

sealed trait A
case class Sub1() extends A
case object Sub2 extends A

def test(x: A | Null): Int =
  if x == null then return 0
  x match
    case Sub1() => 1
    case Sub2 => 2

Output

-- [E007] Type Mismatch Error: try/ft.scala:9:9 --------------------------------
9 |    case Sub2 => 2
  |         ^^^^
  |         Found:    Sub2.type
  |         Required: (x : A | Null) & A
  |         pattern type is incompatible with expected type
  |
  | longer explanation available when compiling with `-explain`

Expectation

No error since Sub2 is a valid subtype of A. The problem is that the selector x gets typed as x.type & A instead of x.type (in toNotNullTermRef) which means the call to .widen in https://github.com/lampepfl/dotty/blob/484be60846be17acee74cfe1c6ea16c10894303f/compiler/src/dotty/tools/dotc/typer/Typer.scala#L1750 doesn't actually widen the singleton.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions