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

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

Error

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

// Add an explicit return type
def example(x: Int): Int =
  if x > 0 then return x
  0
// Or avoid using return (preferred in Scala)
def example(x: Int): Int =
  if x > 0 then x
  else 0