1

Lift 在他们的 Comet Actors 实现中使用了 PartialFunction,你通常会在你的类中得到这个:

override def lowPriority: PartialFunction[Any,Unit] = {
  case MyCaseClass1(a)        => do something here
  case MyCaseClass2(a)        => do something here
  case AlwaysPresentCaseClass => default action
}

我想做的,我不确定是否有可能拆分部分函数,​​以便最后一个案例可以移动到一个特征中。

所以当我有一个新的彗星演员时,我只是这样做:

class MyNewComet extends MyActorTrait {
  override def lowPriority: PartialFunction[Any,Unit] = {
    case MyCaseClass1(a)        => do something here
    case MyCaseClass2(a)        => do something here
  }
}

不知何故,特征 MyActorTrait 将缺少

case AlwaysPresentCaseClass => default action
4

2 回答 2

9

您可以使用以下方法组合部分函数orElse

val f1: PartialFunction[Any, String] = {
  case 22 => "hallo"
}
val f2: PartialFunction[Any, String] = {
  case "rara" => "welt"
}

val f = f1 orElse f2 // f falls back to f2 if undefined in f1
f(22)
f("rara")
于 2011-07-27T02:19:26.190 回答
0

Try this:

trait MyActorTrait extends /* whatever class provides lowPriority */ {
   def default: PartialFunction[Any, Unit] = {
           case AlwaysPresentCaseClass => default action
   }

   abstract override def lowPriority: PartialFunction[Any,Unit] =
       super.lowPriority orElse default
}

The only problem is that you can't do MyNewComet extends MyActorTrait. Instead, you can either have class MyNewCometDefault extends MyNewComet with MyActorTrait, or new MyNewComet with MyActorTrait.

于 2011-07-27T17:49:24.070 回答