E022: By-Name 파라미터 미지원

E022: By-Name 파라미터 미지원 (By Name Parameter Not Supported)

이 에러는 by-name 파라미터 타입(=> T)이 허용되지 않는 문맥(예: 튜플 타입)에서 사용될 때 발생해요.

출처: Scala 3 Reference

본문

By-name 파라미터는 참조될 때만 평가되는 함수처럼 동작해서, 파라미터의 지연 평가(lazy evaluation)를 가능하게 해요.

By-name 파라미터 타입(=> T)는 특정 문맥에서만 허용돼요:

다음 문맥에서는 허용되지 않습니다:

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")

더 알아보기

  • By-name 파라미터에 대한 자세한 내용은 "Method Definitions / By-Name Parameters" 관련 문서를 참고하세요.