【发布时间】:2014-08-08 18:53:00
【问题描述】:
我有两个关于 Scala 中嵌套类型的问题。
想象一下我有这种特质;
trait ScanList[E] {
sealed trait Command
case object Recover extends Command
case class Remove(item: E) extends Command
sealed trait Event
case class Removed(item: E) extends Event
}
现在我想像这样写一个通用特征(问题在模式匹配中编码为注释):
trait ScanListProcessor[E] {
type SL = ScanList[E]
def process(msg: SL#Command) = {
msg match {
case u:SL#Remove => // how can instantiate SL#Removed here?
case SL#Recover => //cannot match on nested objects?
}
}
}
使用 trait 的原因是我可以派生 ScanList 的新实现。在这个特征中,我也有像def shouldProcess(item: E): Boolean 这样的操作。对于ScanList[E] 的每个实现,我想编写如上所示的通用行为。
- 如何对泛型类型的嵌套对象进行模式匹配?
- 是否可以从类型构造函数进行实例化?例如:
SL#Removed?我想拥有一个泛型参数并尝试从中构造一个值是一样的,类型类会解决这个问题吗?
【问题讨论】: