Skip to content

Unexpected type mismatch: found Int | Null, required Long #2833

Closed
@olafurpg

Description

@olafurpg
object a {
  val x: scala.Any =
    if (true)
      0L
    else if (false)
      (0: Int)
    else
      null
}

reports

-- [E007] Type Mismatch Error: foo.scala:5:9 -----------------------------------
5 |    else if (false)
  |         ^
  |         found:    Int | Null
  |         required: Long
  |
6 |      (0: Int)
7 |    else
8 |      null

I expected it to typecheck since Int, Long and Null are a subtype of Any. scalac does not report an error.

Also, note that the reported position is a bit weird. It gets more confusing inside a pattern match

object a {
  val x: scala.Any = 1 match {
    case 1 =>
      if (true) (0: Int) else null
    case 2 =>
      if (false) 0L else null
  }
}


// reports

-- [E007] Type Mismatch Error: foo2.scala:3:11 ---------------------------------
3 |    case 1 =>
  |           ^
  |           found:    Int | Null
  |           required: Long
  |
4 |      if (true) (0: Int) else null
-- [E007] Type Mismatch Error: foo2.scala:5:11 ---------------------------------
5 |    case 2 =>
  |           ^
  |           found:    Long | Null
  |           required: Long
  |
6 |      if (false) 0L else null

three errors found

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions