Back to Scala3

E091: Return Outside Method Definition

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

3.8.41.5 KB
Original Source

E091: Return Outside Method Definition

This error is emitted when a return statement is used outside of a method definition.

The return keyword may only be used within method definitions. It cannot be used in constructors, anonymous functions, or at the top level.


Example

scala
val x = return 42

Error

scala
-- [E091] Syntax Error: example.scala:1:8 --------------------------------------
1 |val x = return 42
  |        ^^^^^^^^^
  |        return outside method definition
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | You used return in the top-level definitions in package <empty>.
  | return is a keyword and may only be used within method declarations.
   -----------------------------------------------------------------------------

Solution

scala
// Simply use the value directly
val x = 42
scala
// Use return only inside methods
def getValue: Int = return 42  // but even here, avoid return
def getBetterValue: Int = 42   // preferred style
<!-- 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>