Scala 中的部分函数是否有类似 Map.keySet 的东西?

Is there something like Map.keySet for a partial function in scala?

更具体地说,我有:

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)
  }
}

我是这样使用的:

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
}

当然这样简化了一些,但是报表功能是必须的。

一些历史:我首先使用 Map 实现了它,但后来我将其更改为 PartialFunction 以支持以下 override def myMap: MethodMap = if (one) map1 else map2.

任何重构我的代码以支持所有内容的建议也非常感谢。

没有。 PartialFunction 可以在无限集上定义(而且通常是)。例如。在这些情况下,您期望 report 到 return 是什么:

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)
  }
}

Some history: I first had it implemented using Map but then I changed it to PartialFunction in order to support the last line in second part.

为什么?这与 Map.

一样有效

In your solution, is there any way to define the domain of the partial function to be the finite set keys

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

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