Back to Scala3

E225: Infer Union Warning

docs/_docs/reference/error-codes/E225.md

3.8.41.8 KB
Original Source

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

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

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

Warning

scala
-- [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:

scala
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:

scala
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

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

class Characters:
  def favorite = Pair('1', '2')
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>