E035: Unbound Wildcard Type — 묶이지 않은 와일드카드 타입이에요

E035: Unbound Wildcard Type — 묶이지 않은 와일드카드 타입이에요

와일드카드 타입(wildcard type) 문법(_ 또는 ?)을 구체적인 타입에 묶일 수 없는 위치에서 사용했을 때 이 에러가 나와요.

출처: Scala 3 Reference

본문

와일드카드를 와일드카드가 아닌 타입으로 바꿔주면 돼요. 타입이 중요하지 않다면 와일드카드를 Any로 바꿔보는 것도 방법이에요.

이 에러는 주로 이런 곳에서 발생해요.

  • 파라미터 목록: def foo(x: _) = ...
  • 생성자의 타입 인자: val foo = List[?](1, 2)
  • 타입 바운드: def foo[T <: _](x: T) = ...
  • valdef의 타입: val foo: _ = 3

예제 (Example)

def example(x: ?) = x

오류 메시지 (Error)

-- [E035] Syntax Error: example.scala:1:15 -------------------------------------
1 |def example(x: ?) = x
  |               ^
  |               Unbound wildcard type
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The wildcard type syntax (_) was used where it could not be bound.
  | Replace _ with a non-wildcard type. If the type doesn't matter,
  | try replacing _ with Any.
  |
  | Examples:
  |
  | - Parameter lists
  |
  |   Instead of:
  |     def foo(x: _) = ...
  |
  |   Use Any if the type doesn't matter:
  |     def foo(x: Any) = ...
  |
  | - Type arguments
  |
  |   Instead of:
  |     val foo = List[?](1, 2)
  |
  |   Use:
  |     val foo = List[Int](1, 2)
  |
  | - Type bounds
  |
  |   Instead of:
  |     def foo[T <: _](x: T) = ...
  |
  |   Remove the bounds if the type doesn't matter:
  |     def foo[T](x: T) = ...
  |
  | - val and def types
  |
  |   Instead of:
  |     val foo: _ = 3
  |
  |   Use:
  |     val foo: Int = 3
   -----------------------------------------------------------------------------

해결 방법 (Solution)

타입이 중요하지 않다면 Any, 제네릭 동작이 필요하다면 타입 파라미터, 아니면 구체적인 타입을 지정하면 돼요.

// Use Any if the type doesn't matter
def example(x: Any) = x
// Use a type parameter for generic behavior
def example[T](x: T): T = x
// Specify a concrete type
def example(x: Int) = x

더 알아보기 (Learn more)