这个问题仍未得到答复,尽管它被标记为重复。
从http://www.scala-lang.org/files/archive/spec/2.12/08-pattern-matching.html#type-patterns我们可以编写以下代码
假设我有一个类型类:
trait T[A] {
def getType: String
}
object T {
def apply[A](implicit t: T[A]): T[A] = t
implicit object TInt extends T[Int] {
def getType = "Int"
}
implicit object TString extends T[String] {
def getType = "String"
}
}
和使用我的类型类
的类型化类class C[A] {
def func(implicit t: T[A]) = t.getType
}
当我尝试代表C[A]
时,我收到错误
val list: List[Int] = 1 :: 2 :: Nil
val result =
list match {
case list: List[t] => new C[t] //type parameter 't'
}
result.func //Error: could not find implicit value for parameter t: T[t]
在模式匹配中使用类型参数的情况有什么问题?
更新 另一个简单的例子:
val array =
List[Int](1, 2, 3, 4) match {
case l: List[a] => scala.collection.mutable.ArrayBuffer[a]()
}
array += 1
错误:type mismatch; found: Int(1), required: a array += 1