Back to Scala3

E190: Pure Unit Expression

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

3.8.41.9 KB
Original Source

E190: Pure Unit Expression

This warning is emitted when a pure non-Unit expression is discarded in a context expecting Unit.

When an expression of non-Unit type is used where Unit is expected, the compiler inserts a discarding conversion. If the expression is pure (has no side effects), this conversion produces no useful effect and the code is effectively equivalent to ().


Longer explanation:

As this expression is not of type Unit, it is desugared into { expression; () }. Here the expression is a pure statement that can be discarded. Therefore the expression is effectively equivalent to ().


Example

scala
def example: Unit = 42

Error

scala
-- [E190] Potential Issue Warning: example.scala:1:20 --------------------------
1 |def example: Unit = 42
  |                    ^^
  |   Discarded non-Unit value of type Int. Add `: Unit` to discard silently.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | As this expression is not of type Unit, it is desugared into `{ 42; () }`.
  | Here the `42` expression is a pure statement that can be discarded.
  | Therefore the expression is effectively equivalent to `()`.
   -----------------------------------------------------------------------------

Solution

Return Unit explicitly:

scala
def example: Unit = ()

Or change the return type if you want to return the value:

scala
def example: Int = 42
<!-- 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>