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