使用类型变量和类型类匹配类型模式

时间:2016-12-17 21:25:00

标签: scala generics pattern-matching type-inference

这个问题仍未得到答复,尽管它被标记为重复。

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

0 个答案:

没有答案
相关问题