Skip to content

Type inference for union types is surprising #10108

Closed
@odersky

Description

@odersky

Minimized example

object Test1:
  val x: Int | String = 1
  val y = x
  val z: Int | String = y

Output

4 |  val z: Int | String = y
  |                        ^
  |                        Found:    (Test1.y : Any)
  |                        Required: Int | String

The problem is that a union type is widened at each inference step. Hence the declared type Int | String of x gets lost in the type of y.

This widening can lead to mysterious behavior in the type checker. Here's an example:

object Test2:
  type Sig = Int | String
  def consistent(x: Sig, y: Sig): Boolean = x == y

  def consistentLists(xs: List[Sig], ys: List[Sig]): Boolean =
       xs.corresponds(ys)(consistent)        // OK
    || xs.corresponds(ys)(consistent(_, _))  // error, found: Any, required: Int | String

The first corresponds tests succeeds, but if we eta-expand the argument to consistent(_, _) it fails.

Expectation

I hope we can come up with a more predictable type inference algorithm.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions