功能不接受任何参数

时间:2016-12-19 05:50:52

标签: scala

我有一个不接受任何参数的函数并返回一个部分函数。

def receive:PartialFunction[Any,Unit]={
case "hello"=>println("Got it 1")
case 123=>println("Got it 2")
case true=>println("Got it 3")
}
receive("hello")

我无法理解这个函数调用语法。如何将字符串传递给receive函数以及case函数如何执行?

但是,我也无法理解以下代码:

def receive():PartialFunction[Any,Unit]={
case "hello"=>println("Got it 1")
case 123=>println("Got it 2")
case true=>println("Got it 3")
}
val y=receive()
y("hello")

2 个答案:

答案 0 :(得分:3)

  1. { case ... }这样的匿名部分功能是

    的缩写
    new PartialFunction[Any, Unit] {
      def isDefinedAt(x: Any) = x match {
        case "hello" => true
        case 123 => true
        case true => true
        case _ => false
      }
    
      def apply(x: Any) = x match {
        case "hello" => println("Got it 1")
        case 123 => println("Got it 2")
        case true => println("Got it 3")
      }
    }
    

    [Any, Unit]来自此情况下的预期类型。)

  2. 由于receive不是带参数的方法,receive("hello")receive.apply("hello")的缩写。

答案 1 :(得分:1)

我会尝试解释你问题的第二部分。正如您所看到的,接收方法的两个定义之间存在细微差别,一个带括号,另一个没有。正如之前的回答所说,请致电:

val func: Any => Any = ???
func(42)

由scala解析器转换为:

func.apply(42)

对于部分函数(以及定义了apply方法的任何类型的对象)也是如此。所以你的调用会被重写为: 第一:

val y = receive()
y.apply("hello")

第二

receive.apply("hello")

也许你现在可以看到差异?当接收到(空的但是现有的)括号时,你不能写receive.apply。

相关问题