Back to Scala3

E045: Recursive Value Needs Result Type

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

3.8.41.7 KB
Original Source

E045: Recursive Value Needs Result Type

This error is emitted when a recursive value definition doesn't have an explicit type annotation.

When a value references itself in its definition (either directly or through lazy evaluation), the compiler needs an explicit type to break the cycle and determine the value's type.


Example

scala
lazy val ones = 1 #:: ones

Error

scala
-- [E045] Cyclic Error: example.scala:1:22 -------------------------------------
1 |lazy val ones = 1 #:: ones
  |                      ^
  |Recursive lazy value ones needs type
  |
  |The error occurred while trying to compute the signature of lazy value ones
  |  which required to type the right hand side of lazy value ones since no explicit type was given
  |  which required to compute the signature of lazy value ones
  |
  | Run with both -explain-cyclic and -Ydebug-cyclic to see full stack trace.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The definition of lazy value ones is recursive and you need to specify its type.
   -----------------------------------------------------------------------------

Solution

scala
// Add an explicit type annotation
lazy val ones: LazyList[Int] = 1 #:: ones
<!-- 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>