【问题标题】:How to interpret this def that uses a PartialFunction?如何解释这个使用 PartialFunction 的 def?
【发布时间】:2015-04-29 18:43:33
【问题描述】:

我仍然习惯于 Scala 中的 PartialFunction 概念。 我遇到了以下我无法理解的声明:

更新: def msgsToGet: PartialFunction[Any, Unit] 在 trait 中定义如下:

trait MyActorTrait {
    palindrome: String => def msgsToGet: PartialFunction[Any, Unit]
    //After the answers I received, I understand that the "def msgsToGet:      //PartialFunction[Any, Unit]" represents the LHS of an abstract (as yet)     //unimplemented function (no function body yet)

}

现在,这是什么意思? 我知道'def'表示一个函数。在本例中,它是一个名为 msgsToGet 的函数。

然后是一个冒号 (:)。好吧,直到现在,我一直认为“冒号后,是类型,这就是我迷路的地方。 好吧,是不是和以下一样:

def msgsToGet(): PartialFunction[Any, Unit]

[一个不接受参数并返回PartialFunction[Any, Unit]类型的函数。

PartialFunction[Any, Unit] 对我来说有点像返回类型。但是没有函数体。请问这是怎么回事?

这是一个更长但可读的语法糖吗?

请帮我解释一下..

【问题讨论】:

    标签: scala


    【解决方案1】:

    如果没有函数体,那么它就是一个抽象方法。它是在特征上还是在抽象类上?抽象方法,如 Java,表示实现类必须定义方法。

    您的分析是正确的:它是一个名为“msgsToGet”的函数,它不带参数并返回PartialFunction[Any, Unit] 类型的对象。

    这是一个例子:

    trait SomeTrait {
      def msgsToGet: PartialFunction[Any, Unit]
    }
    
    class SomeClass extends SomeTrait {
      def msgsToGet: PartialFunction[Any, Unit] = { 
        case x => println(x)      
      } // a case block is a partial function, so we can return this block from the function
    }
    
    val c = new SomeClass
    val f = c.msgsToGet    // takes no parameters, returns a partial function
    f("hey")               // we can call the partial function, which takes an Any parameter
    // prints "hey"
    

    【讨论】:

    • 很好的答案。我会选择你的答案作为正确的答案。
    • 很好的答案。我保证一旦我能够做到这一点,就会支持你的回答。直到现在我才知道 case 块是一个偏函数。
    【解决方案2】:

    几乎一样

    def msgsToGet(): PartialFunction[Any, Unit]
    

    Scala 允许没有参数列表的方法(而不是一个空参数列表)。

    在字节码中,这两者是相同的,但在惯用的 Scala 中,对于无副作用的方法,尤其是访问器,不首选参数列表。如果该方法有副作用,则首选空参数列表。

    【讨论】:

    • 又一个天真的问题:如果没有函数体,函数如何返回 PartialFunction[Any, Unit] 类型的值?
    • 哦,这只是意味着它是一个抽象方法。 Scala 没有抽象关键字。如果 def/var/val 没有主体,则它是抽象的。
    • 您直接回答了我的问题。 @dhg 的回答和您的回答都非常好,令人大开眼界。好吧..我会把你的问题标记为正确答案
    猜你喜欢
    • 2015-10-11
    • 2020-05-09
    • 1970-01-01
    • 2019-02-08
    • 2018-04-02
    • 2010-10-15
    • 2012-03-17
    • 2014-04-22
    • 2019-11-19
    相关资源
    最近更新 更多