【发布时间】:2020-05-02 17:56:07
【问题描述】:
好吧,我不知道这段代码有什么问题:
import scala.reflect.runtime.universe._
trait Key extends Product
case class SomeKey(a: Int, b: String) extends Key
case class SomeOtherKey(a: Int, b: String, c:Boolean) extends Key
trait MyTrait[T <: Key] {
def someField: Int
def someFunc(implicit tTypeTag: TypeTag[T]): Map[T, Int] = {
typeOf(tTypeTag) match {
case t if t =:= typeOf[SomeKey] => Map(SomeKey(1,"2") -> 1)
case t if t =:= typeOf[SomeOtherKey] => Map(SomeOtherKey(1,"2",true) -> 2)
}
}
}
如果从扩展MyTrait[SomeKey] 的案例类中调用someFunc,我希望(示例过于简单)能够返回Map[SomeKey, Int]。并从MyTrait[SomeOtherKey]返回Map[SomeOtherKey, Int]
case class MyClass(val s: Int) extends MyTrait[SomeKey] {
override def someField = s
}
这里MyClass 的新实例在调用someFunc 时应该返回Map[SomeKey, Int]。
但它甚至没有编译,编译器抱怨模式匹配的每一行:
type mismatch;
found : (Playground.this.SomeKey, Int)
required: (T, Int)
或
type mismatch;
found : (Playground.this.SomeOtherKey, Int)
required: (T, Int)
【问题讨论】:
-
您能否详细说明您需要了解的有关特定类型的密钥的哪些信息?此外,该方法是否必须在相同的特征中定义?还是可以作为扩展方法添加?
标签: scala types pattern-matching