【发布时间】:2015-02-10 10:36:23
【问题描述】:
我有一个内部案例类,特别是来自this 问题的事件,并且想要匹配它,包括外部对象:
class Player {
var _life = 20
def life = _life
def gainLife(life: Int) = execute(GainLife(life))
case class GainLife(life: Int) extends Event {
def execute() = _life += life
}
}
我可以轻松地编写一个效果(部分函数)来替换特定玩家的生活事件:
//gain twice as much life
def effect(player: Player): ReplacementEffect = {
case player.GainLife(x) => player.GainLife(x * 2)
}
但是,我不能对其他玩家做同样的事情。我最接近的是:
//only you gain life
def effect2(player: Player): ReplacementEffect = {
case evt: Player#GainLife => player.GainLife(evt.life)
}
但是 1) 这甚至会用新的生命增益替换您自己的生命增益,2) 我无法引用最初在函数中获得生命的玩家,以及 3) 我错过了以这种方式直接匹配 life 的机会。
这可以使用与路径无关的类型来表达,例如
case Player.GainLife(_player, life) if _player != player => GainLife(player, life)
理想情况下,我想要类似的东西
case _player.GainLife(life) if _player != player => player.GainLife(life)
这是否可能,或者我可以解决这个问题吗?还是我必须求助于让 GainLife 嵌套?
【问题讨论】:
标签: scala pattern-matching case-class