E225: Infer Union Warning

This warning is emitted when type of expressions is inferred to be a union type, which may indicate a programming error.

Union types are inferred when the compiler needs to find a common type for two or more values of different types. While sometimes intentional, an inferred union type often signals that values of incompatible types are being mixed unintentionally.

This warning is enabled with the -Winfer-union compiler flag.


Example

class Pair[A](left: A, right: A)

class Characters:
  def favorite = Pair("1", '2')

Warning

-- [E225] Type Warning: example.scala:4:17 -------------------------------------
4 |  def favorite = Pair("1", '2')
  |                 ^^^^
  |               A type argument was inferred to be union type String | Char
  |               This may indicate a programming error.

Solution

If the union type is intentional, provide the type argument explicitly to silence the warning:

class Pair[A](left: A, right: A)

class Characters:
  def favorite = Pair[String | Char]("1", '2')

Or use a common supertype if the union was unintentional:

class Pair[A](left: A, right: A)

class Characters:
  def favorite = Pair[Matchable]("1", '2')

If the union type was not expected, unsure the correctness of the code

class Pair[A](left: A, right: A)

class Characters:
  def favorite = Pair('1', '2')