如何在Scala中声明新的部分函数类型

时间:2012-03-02 17:14:37

标签: scala

以下是我对语言的理解。

如何声明新的特定部分函数类型。假设我需要声明许多部分定义的函数,接受一个MyClass类并返回一个字符串。如果我尝试:

class mypf extends PartialFunction[MyClass, String]
val myinstance: mypf = { case ... }

Scala抱怨mypf应该是抽象的。我该怎么办?完全这样做是不是一个坏主意?如果是这样,为什么?

3 个答案:

答案 0 :(得分:8)

虽然它一般不能解决您的问题,但在特定情况下可能有所帮助:

scala> type mypf = PartialFunction[Int, String]
defined type alias mypf

// type alias for PartialFunction

scala> val x: mypf = {case x: Int if x > 10 => "More than ten"}
x: mypf = <function1>

答案 1 :(得分:6)

如果您想要的是PartialFuncion [MyClass,String]的别名,那么您应该

type MyPf = PartialFunction[MyClass, String]

这个声明在顶级是不可能的,它必须在一个对象内。如果你想让它看起来非常像顶级声明,那么你可以在包对象中声明类型。

进一步,做

abstract class mypf extends PartialFunction[MyClass, String] 

是合法的(它显然必须是抽象的,它缺少应用的实现并且是定义的)。但是,{case x => ...}之类的表达式将是PartialFunction类型,而不是您的类型,因此您的类型将不方便。

即使没有失去lteterals,使用继承只是为了获得别名的用途有限。如果您执行class MyClass extends Something<With, Lots, Of, Parameters>MyClass将在创建实例时提供帮助,但声明类型MyClass的方法参数会阻止过度限制方法。

答案 2 :(得分:2)

不必为整个输入域定义PartialFunction,因此特征将applyisDefinedAt定义为抽象。 因此,你必须像这样实现上述方法:

val myInstance = new PartialFunction[Int, String] {
  override def apply(i: Int): String = {
    if (i < 100)
      "Valid " + i
    else
      "Undefined"
  }

  override def isDefinedAt(i: Int): Boolean = i < 100
}

您无需明确说出override,但有时这样做很有帮助。

相关问题