简体   繁体   English

在 Scala 中进行模式匹配时,类型参数会限制编译器错误

[英]type parameter bounds compiler error while pattern matching in Scala

Why does the line为什么线路

case Wrapper(rv: Ref[_]) => rv :: state

Not compile if如果不编译

def f(r: Ref[_]): List[Ref[_]] = r :: state

compiles just fine?编译就好了?

Is there a way to get this code to compile while preserving as much type safety as possible ?有没有办法在尽可能多地保留类型安全的同时编译此代码?

These lines are taken from the following self contained example:这些行取自以下自包含示例:

object Test2 {

  trait Entity[T <: Entity[T]]


  case class Ref[T <: Entity[T]](t: T)

  type State[T <: Entity[T]] = List[Ref[T]]

  private var state: State[_] = ???

  trait SomeWrapper
  case class Wrapper[T <: Entity[T]](at: Ref[T]) extends SomeWrapper

  def matcher(w: SomeWrapper): Unit = w match {
    case Wrapper(rv: Ref[_]) => rv :: state // does not compile
    case _ => ???
  }

  def f(r: Ref[_]): List[Ref[_]] = r :: state // if this compiles fine, why the above does not compile ?


}

the code above gives the following compiler error:上面的代码给出了以下编译器错误:

Error:(40, 36) type arguments [Any] do not conform to class Ref's type parameter bounds [T <: Test2.Entity[T]]
    case Wrapper(rv: Ref[_]) => rv :: state // does not compile

Looks like a bug to me:对我来说看起来像一个错误:

w match {
  case Wrapper(rv)         => (rv: Ref[_]) :: state // Compiles
  case Wrapper(rv: Ref[_]) => (rv: Ref[_]) :: state // Compiles
  case Wrapper(rv)         => rv           :: state // Doesn't Compile
  case Wrapper(rv: Ref[_]) => rv           :: state // Doesn't Compile???
  case e: Wrapper[_]       => e.at         :: state // Compiles
  case _ => ???
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM