0

More specifically, I have:

case class Key (key: String)
abstract class abstr {
  type MethodMap = PartialFunction[Key,  String => Unit]
  def myMap: MethodMap // abstract

  def useIt (key: Key, value: String) = {
    val meth = myMap(key)
    meth(value)
  }

  def report = {
    for (key <- myMap.keySet) // how to do this
      println("I support "+key)
  }
}

I use it like this:

class concrete extends abstr {
  var one: Boolean
  def method1(v: String): Unit = ???
  def method2(v: String): Unit = ???

  def map1: MethodMap = {
    case Key("AAA") => method1
  }
  def map2: MethodMap = {
    case Key("AAA") => method2
  }

  override def myMap: MethodMap = if (one) map1 else map2
}

Of course, this is somewhat simplified, but the report function is necessary.

Some history: I first had it implemented using Map but then I changed it to PartialFunction in order to support the following override def myMap: MethodMap = if (one) map1 else map2.

Any suggestion to refactor my code to support everything is also appreciated.

4

1 回答 1

3

No.PartialFunction可以在无限集上定义(并且经常是)。例如,您希望report在这些情况下返回什么:

class concrete2 extends abstr {
  def myMap = { case Key(_) => ??? }
}

或者

class concrete2 extends abstr {
  def myMap = { case Key(key) if key.length > 3 => ??? }
}

? 如果你有一个你感兴趣的有限值列表,你可以做

abstract class abstr {
  type MethodMap = PartialFunction[Key,  String => Unit]
  def myMap: MethodMap // abstract
  val keys: Seq[Key] = ...

  def report = {
    for (key <- keys if myMap.isDefined(key))
      println("I support "+key)
  }
}

一些历史:我首先使用 Map 实现它,但后来我将其更改为 PartialFunction 以支持第二部分的最后一行。

为什么?这也适用于Map.

在您的解决方案中,有没有办法将偏函数的域定义为有限集keys

def f: MethodMap = { case key if keys.contains(key) => ... }

当然,域不是类型的一部分。

于 2015-12-05T10:47:57.847 回答