타입 바운드에 부합하지 않음

타입 바운드에 부합하지 않음 (Does Not Conform To Bound)

타입 인자가 타입 매개변수에 선언된 타입 바운드(type bound)를 만족하지 못할 때 나오는 에러예요.

출처: Scala 3 Reference

본문

타입 인자가 타입 매개변수에 선언된 타입 바운드를 만족하지 못하면 이 에러가 발생해요.

타입 매개변수는 상한 바운드(upper bound, <:)와 하한 바운드(lower bound, >:)를 가질 수 있어요. 타입 인자를 제공할 때는 이 바운드를 반드시 만족해야 해요. 상한 바운드는 타입 인자가 그 바운드의 서브타입이어야 한다는 뜻이고, 하한 바운드는 수퍼타입이어야 한다는 뜻이에요.

예시

trait A
trait B extends A
trait C extends B
class Contra[-T >: B]

def example =
    val a: Contra[A] = ???
    val b: Contra[B] = ???
    val c: Contra[C] = ???

에러 메시지

-- [E057] Type Mismatch Error: example.scala:9:18 ------------------------------
9 |    val c: Contra[C] = ???
  |                  ^
  |                  Type argument C does not conform to lower bound B
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | I tried to show that
  |   B
  | conforms to
  |   C
  | but none of the attempts shown below succeeded:
  |
  |   ==> B  <:  C  = false
  |
  | The tests were made under the empty constraint
   -----------------------------------------------------------------------------

해결 방법

// Use a types that conforms to the bound
trait A
trait B extends A
trait C extends A

class Contra[-T >: B]

def example =
    val a: Contra[A] = ???
    val b: Contra[B] = ???
// Or change the type bound if appropriate
trait A
trait B extends A
trait C extends B

class Contra[-T >: C]

def example =
    val a: Contra[A] = ???
    val b: Contra[B] = ???
    val c: Contra[C] = ???

더 알아보기

  • 바운드에 부합하는 타입을 쓰거나, 상황에 맞다면 타입 바운드 자체를 조정하면 돼요.