E017: 바인딩되지 않은 플레이스홀더 파라미터

E017: 바인딩되지 않은 플레이스홀더 파라미터 (Unbound Placeholder Parameter)

이 에러는 밑줄(_) 플레이스홀더 문법이 파라미터에 바인딩될 수 없는 문맥에서 사용될 때 발생해요. 변수 바인딩을 명시적으로 작성하는 걸 고려해 보세요.

출처: Scala 3 Reference

본문

_를 변수(예: x)로 바꾸고 해당되는 곳에 x =>를 추가하면 해결할 수 있어요.

잘못된 사용의 흔한 예:

Example

val x = _

Error

-- [E017] Syntax Error: example.scala:1:8 --------------------------------------
1 |val x = _
  |        ^
  |        Unbound placeholder parameter; incorrect use of _
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The _ placeholder syntax was used where it could not be bound.
  | Consider explicitly writing the variable binding.
  |
  | This can be done by replacing _ with a variable (eg. x)
  | and adding x => where applicable.
  |
  | Example before:
  |
  | { _ }
  |
  | Example after:
  |
  | x => { x }
  |
  | Another common occurrence for this error is defining a val with _:
  |
  | val a = _
  |
  | But this val definition isn't very useful, it can never be assigned
  | another value. And thus will always remain uninitialized.
  | Consider replacing the val with var:
  |
  | var a = _
  |
  | Note that this use of _ is not placeholder syntax,
  | but an uninitialized var definition.
  | Only fields can be left uninitialized in this manner; local variables
  | must be initialized.
  |
  | Another occurrence for this error is self type definition.
  | The _ can be replaced with this.
  |
  | Example before:
  |
  | trait A { _: B => ...
  |
  | Example after:
  |
  | trait A { this: B => ...
   -----------------------------------------------------------------------------

Solution

// Use an explicit lambda with a named parameter
val f: Int => Int = x => x + 1
// The placeholder syntax works in lambda contexts with clear types
val f: Int => Int = _ + 1
// For uninitialized fields, use var (only in classes, not local scope)
class Example:
  var x: Int = scala.compiletime.uninitialized  // Uninitialized field, defaults to 0
// Use wildcard in pattern matching
val list = List(1, 2, 3)
val head = list match
  case h :: _ => h
  case _ => 0

더 알아보기

  • 플레이스홀더 문법과 언더스코어의 다양한 쓰임은 사양서의 "Wildcards / Placeholder" 관련 문서를 참고하세요.