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

class LazyHolder(val value: => Int)

Error

-- [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

// Use a regular parameter and a lazy val
class LazyHolder(valueInit: => Int):
  lazy val value: Int = valueInit
// Or use a function type
class LazyHolder(getValue: () => Int):
  def value: Int = getValue()
// Or simply use a regular val parameter
class LazyHolder(val value: Int)