St.*_*St. 5 generics scala type-inference pattern-matching
尽管被标记为重复,但这个问题仍然没有得到答复.
从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"
}
}
Run Code Online (Sandbox Code Playgroud)
和使用我的类型类的类型化的类
class C[A] {
def func(implicit t: T[A]) = t.getType
}
Run Code Online (Sandbox Code Playgroud)
当我尝试典型时,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]
Run Code Online (Sandbox Code Playgroud)
在模式匹配中使用类型参数的情况有什么问题?
更新另一个简单示例:
val array =
List[Int](1, 2, 3, 4) match {
case l: List[a] => scala.collection.mutable.ArrayBuffer[a]()
}
array += 1
Run Code Online (Sandbox Code Playgroud)
错误: type mismatch; found: Int(1), required: a array += 1
| 归档时间: |
|
| 查看次数: |
115 次 |
| 最近记录: |