我写了一个实现命令设计模式的类:
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))
}
帮我 :(