【发布时间】:2012-08-02 16:38:59
【问题描述】:
我写了一个实现command design pattern的类:
class MyCommand[-T, +R](val name: String, val execute: T => R)
,准备两个命令并存储在一个 MutableList 中:
val commands = new mutable.MutableList[MyCommand[Nothing, Any]]
commands += new MyCommand[String, String]("lower", s => s.toLowerCase())
commands += new MyCommand[Date, Long]("time", d => d.getTime)
然后我有两个数据要执行:
val data = Array("StRiNG", new Date())
对我来说问题是我不知道如何确定哪个数据适用于命令:
data.foreach {
d => commands.foreach {
c =>
// println(c.execute(d)) if d is applicable to c.execute().
}
}
我尝试的是与类型规范进行模式匹配,但会产生语法错误:
c.execute match {
case m: (d.getClass => Any) => println(c.execute(d))
}
帮帮我:(
【问题讨论】:
-
请说明您的具体问题。你想做什么?
-
我提出了一个实际上并没有像我预期的那样工作的解决方案。你能澄清数据的来源吗?我认为当您需要使用 Nothing 时,会发生一些非常奇怪的事情:)
标签: scala types covariance contravariance