Back to Scala3

E055: Var Val Parameters May Not Be Call By Name

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

3.8.41.9 KB
Original Source

E055: Var Val Parameters May Not Be Call By Name

This error is emitted when a val or var parameter of a class or trait is declared as call-by-name (using => T syntax).

var and val parameters of classes and traits may not be call-by-name because they need to be stored as fields. If you want the parameter to be evaluated on demand, consider making it just a parameter and providing a def in the class.


Example

scala
class LazyHolder(val value: => Int)

Error

scala
-- [E055] Syntax Error: example.scala:1:28 -------------------------------------
1 |class LazyHolder(val value: => Int)
  |                            ^^
  |                            val parameters may not be call-by-name
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | var and val parameters of classes and traits may no be call-by-name. In case you
  | want the parameter to be evaluated on demand, consider making it just a parameter
  | and a def in the class such as
  |   class MyClass(valueTick: => String) {
  |     def value() = valueTick
  |   }
   -----------------------------------------------------------------------------

Solution

scala
// Use a regular parameter and a lazy val
class LazyHolder(valueInit: => Int):
  lazy val value: Int = valueInit
scala
// Or use a function type
class LazyHolder(getValue: () => Int):
  def value: Int = getValue()
scala
// Or simply use a regular val parameter
class LazyHolder(val value: 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>