E022: By Name Parameter Not Supported

This error is emitted when a by-name parameter type (=> T) is used in a context where it is not allowed, such as in tuple types.

By-name parameters act like functions that are only evaluated when referenced, allowing for lazy evaluation of a parameter.

By-name parameter types (=> T) are only allowed in specific contexts:

  • Method parameters: def func(f: => Boolean)
  • Function type parameters: (=> Int) => String

They are not allowed in:

  • Tuple types
  • Type arguments to generic types (except function types)
  • Other contexts where a regular type is expected

Example

type LazyPair = (=> Int, String)

Error

-- [E022] Syntax Error: example.scala:1:17 -------------------------------------
1 |type LazyPair = (=> Int, String)
  |                 ^^^^^^
  |                 By-name parameter type => Int not allowed here.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | By-name parameters act like functions that are only evaluated when referenced,
  | allowing for lazy evaluation of a parameter.
  |
  | An example of using a by-name parameter would look like:
  | def func(f: => Boolean) = f // 'f' is evaluated when referenced within the function
  |
  | An example of the syntax of passing an actual function as a parameter:
  | def func(f: (Boolean => Boolean)) = f(true)
  |
  | or:
  |
  | def func(f: Boolean => Boolean) = f(true)
  |
  | And the usage could be as such:
  | func(bool => // do something...)
   -----------------------------------------------------------------------------

Solution

// Use a function type instead
type LazyPair = (() => Int, String)
// By-name is allowed in function types
type LazyFunction = (=> Int) => String

def example(f: LazyFunction): String = f(42)
// By-name is allowed in method parameters
def lazyEval(x: => Int, y: String): Unit =
  println(s"$y: $x")