E165: Matchable 경고예요

E165: Matchable 경고예요 (Matchable Warning)

Matchable을 확장하지 않는 타입의 값에 대해 패턴 매칭을 수행할 때 발생하는 경고예요. 미래 Scala 버전에서는 패턴 매칭이 대상을 Matchable 인스턴스로 요구할 거예요.

출처: Scala 3 Reference

본문

Matchable trait은 안전하게 패턴 매칭할 수 있는 타입을 표시해요. 이 제약은 패턴 매칭을 지원하지 않는 타입(예: opaque 타입이나 특정 교집합 타입)으로 인스턴스화될 수 있는 추상 타입에 대한 패턴 매칭에서 발생할 수 있는 문제를 잡는 데 도움을 줘요.

이 경고는 -source:future 또는 -source:future-migration으로 활성화돼요.

Example

//> using options -source:future

def example[T](x: T) = x match {
  case s: String => s
  case _ => ""
}

Error

-- [E165] Type Warning: example.scala:4:10 -------------------------------------
4 |  case s: String => s
  |          ^^^^^^
  |          pattern selector should be an instance of Matchable,
  |          but it has unmatchable type T instead
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | A value of type T cannot be the selector of a match expression
  | since it is not constrained to be `Matchable`. Matching on unconstrained
  | values is disallowed since it can uncover implementation details that
  | were intended to be hidden and thereby can violate paramtetricity laws
  | for reasoning about programs.
  |
  | The restriction can be overridden by appending `.asMatchable` to
  | the selector value. `asMatchable` needs to be imported from
  | scala.compiletime. Example:
  |
  |     import compiletime.asMatchable
  |     def f[X](x: X) = x.asMatchable match { ... }
   -----------------------------------------------------------------------------

Solution

// Constrain the type parameter to Matchable
def example[T <: Matchable](x: T) = x match {
  case s: String => s
  case _ => ""
}
//> using options -source:future

// Or use a more specific type bound
def example[T <: AnyRef](x: T) = x match {
  case s: String => s
  case _ => ""
}

더 알아보기

  • MatchableasMatchable에 대한 자세한 내용은 Scala 3 Reference의 타입 시스템 문서를 참고하세요.