在不指定输入类型的情况下定义高阶函数的巧妙方法

时间:2014-03-14 11:13:08

标签: scala syntax functional-programming

我希望能够在scala中定义这么好的接收函数

sealed trait DoParent
case object DoThis extends DoParent
case object DoThat extends DoParent

object MyApp extends App {

  val receive = {
    case DoThis => println("dothis")
    case DoThat => println("dothat")
  }


  receive(DoThis)

}

但它会生成

missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
  val receive = {
                ^

我现在理解它要求我添加类型,但我希望接收看起来整洁干净(仅定义内部的情况,如图所示,没有类型),因为演员接收看起来像,我缺少什么?

感谢

3 个答案:

答案 0 :(得分:1)

如果我理解正确的话:

val receive: DoParent => Any = {
  case DoThis => println("dothis")
  case DoThat => println("dothat")
}

receive(DoThis)
receive(DoThat)

输出:

dothis
dothat

答案 1 :(得分:1)

问题在于,虽然你知道"如果您希望参数为DoParent类型,则Scala编译器不会。您可以希望它接受例如Any ...这就是为什么您必须使用类型注释您的函数值的原因:

val receive: DoParent => Unit = {
  case DoThis => println("dothis")
  case DoThat => println("dothat")
}

您也可以使用方法而不是函数值:

def receive(x: DoParent) = x match {
  case DoThis => println("dothis")
  case DoThat => println("dothat")
}

答案 2 :(得分:1)

我怀疑是否有类型规范的方法。演员这样做的方式是他们声明接收父母特征,如:

trait WithReceive {
    def receive:PartialFunction[DoParent, Unit] //for some reason this needs to be a def
}

然后让你的对象继承这个特性:

object MyApp extends App with WithReceive {
    def receive = { //this needs to be a def too
        case DoThis => ???
        case DoThat => ???
    }
}

出于某种原因,它需要是一个def,使用val会导致你得到同样的错误。