Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 定义高阶函数而不指定输入类型的简洁方法_Scala_Syntax_Functional Programming - Fatal编程技术网

Scala 定义高阶函数而不指定输入类型的简洁方法

Scala 定义高阶函数而不指定输入类型的简洁方法,scala,syntax,functional-programming,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") }

我希望能够在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 = {
                ^
我现在明白了,它要求我添加类型,但我希望接收看起来整洁干净(只定义里面的案例,如图所示,没有类型),就像演员接收一样,我缺少什么


如果我理解正确,谢谢你:

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

receive(DoThis)
receive(DoThat)
输出:

dothis
dothat

问题是,虽然您“知道”希望参数的类型为
DoParent
,但Scala编译器却不这样做。您可能希望它接受例如
任何
。。。这就是为什么必须使用类型注释函数值:

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

我怀疑是否有办法绕过类型规范。参与者这样做的方式是在父特征中声明receive,例如:

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会导致与您相同的错误。

关于为什么它必须是def,只有一个长的ML线程:有问题,因此可能很快val的RHS也会使用trait中的类型进行类型检查。