Back to Scala3

E126: Value Class Parameter May Not Be Call-By-Name

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

3.8.41.4 KB
Original Source

E126: Value Class Parameter May Not Be Call-By-Name

This error occurs when a value class (a class that extends AnyVal) has a call-by-name parameter (using => T syntax).

Value classes are a special mechanism in Scala that allows defining wrapper classes that avoid runtime allocation overhead. The JVM represents value class instances as their underlying value at runtime. Call-by-name parameters, which are evaluated lazily each time they are accessed, are incompatible with this optimization because they cannot be unboxed to a primitive value.


Example

scala
class Wrapper(x: => Int) extends AnyVal

Error

scala
-- [E126] Syntax Error: example.scala:1:14 -------------------------------------
1 |class Wrapper(x: => Int) extends AnyVal
  |              ^
  |              Value class parameter `x` may not be call-by-name

Solution

scala
// Use a regular (by-value) parameter
class Wrapper(val x: Int) extends AnyVal
scala
// Alternative: If lazy evaluation is needed, consider using a regular class
class Wrapper(x: => Int):
  def value: Int = x
<!-- 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>