Back to Scala3

E089: Missing Return Type With Return Statement

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

3.8.41.6 KB
Original Source

E089: Missing Return Type With Return Statement

This error is emitted when a method contains a return statement but doesn't have an explicit return type.

If a method contains a return statement, it must have an explicit return type. The compiler needs to know the return type to properly type-check the return expression.


Example

scala
def example(x: Int) =
  if x > 0 then return x
  0

Error

scala
-- [E089] Syntax Error: example.scala:2:16 -------------------------------------
2 |  if x > 0 then return x
  |                ^^^^^^^^
  |             method example has a return statement; it needs a result type
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | If a method contains a return statement, it must have an
  | explicit return type. For example:
  |
  | def good: Int /* explicit return type */ = return 1
   -----------------------------------------------------------------------------

Solution

scala
// Add an explicit return type
def example(x: Int): Int =
  if x > 0 then return x
  0
scala
// Or avoid using return (preferred in Scala)
def example(x: Int): Int =
  if x > 0 then x
  else 0
<!-- 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>