Back to Scala3

E019: Missing Return Type

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

3.8.41.6 KB
Original Source

E019: Missing Return Type

This error is emitted when an abstract method declaration is missing its return type. Abstract declarations must have explicit return types. Without a body, the compiler cannot infer the type of the method, so it must be explicitly specified.


Example

scala
trait Foo:
  def bar

Error

scala
-- [E019] Syntax Error: example.scala:2:9 --------------------------------------
2 |  def bar
  |         ^
  |         Missing return type
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | An abstract declaration must have a return type. For example:
  |
  | trait Shape:
  |   def area: Double // abstract declaration returning a Double
   -----------------------------------------------------------------------------

Solution

scala
// Add an explicit return type
trait Foo:
  def bar: Unit
scala
// Or provide an implementation (then type can be inferred)
trait Foo:
  def bar = println("hello")
scala
// For methods with parameters
trait Calculator:
  def add(a: Int, b: Int): Int
  def multiply(a: Int, b: Int): Int
<!-- 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>