Back to Scala3

E103: Illegal Start of Statement

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

3.8.41.7 KB
Original Source

E103: Illegal Start of Statement

This error is emitted when the compiler encounters a token or expression that cannot legally begin a statement in that context.

A statement is an import, export, a definition, or an expression. Some statements are only allowed in certain contexts. This error often occurs when the parser encounters something that looks like it could start a definition but is actually invalid syntax at the top level.

One of the most common cases of this error is using an expression (e.g., method invocation) outside of a class or top-level member definition.


Example

scala
package example

def fa(f: String ?=> Unit): Unit = ???
fa(42)

Error

scala
-- [E103] Syntax Error: example.scala:4:0 --------------------------------------
4 |fa(42)
  |^^
  |Illegal start of toplevel definition
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | A statement is an import or export, a definition or an expression.
  | Some statements are only allowed in certain contexts
   -----------------------------------------------------------------------------

Solution

Wrap the expression in a method definition:

scala
// Wrap the call in a method definition
package example

def fa(f: String ?=> Unit): Unit = ???
def test: Unit = fa(())
<!-- 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>