【问题标题】:Scala: when exactly are function parameter types required?Scala:什么时候需要函数参数类型?
【发布时间】:2011-08-03 16:18:24
【问题描述】:

在 Scala 中定义函数的方式有很多种,这会导致在何时需要函数参数类型时产生混淆。我通常从最简单的定义开始,一直往下走,直到编译器错误消失。我宁愿真正了解它是如何工作的。

例如:

_ + _

(x, y) => x + y

(x: Int, y: Int) => x + y

def sum(x: Int, y: Int) = x + y // as pointed out, this is a method,
                                // which not a function

文档链接的奖励积分。

【问题讨论】:

    标签: scala


    【解决方案1】:

    有一些极端情况,例如:递归方法必须显式类型化,但通常经验法则如下:类型必须来自某个地方。

    它们来自参考部分:

    val function: (Int, Int) => Int = _ + _
    

    或从对象部分:

    val function = (x: Int, y: Int) => x + y
    

    并不重要。 (在 Scala 中!)

    我知道你的问题是关于函数的,但这里有一个类似的例子来说明 Scala 的类型推断:

    // no inference
    val x: HashMap[String, Int] = new HashMap[String, Int]()
    val x: HashMap[String, Int] = new HashMap[String, Int]
    
    // object inference
    val x: HashMap[String, Int] = new HashMap()
    val x: HashMap[String, Int] = new HashMap
    val x: HashMap[String, Int] = HashMap() // factory invocation
    
    // reference inference
    val x = new HashMap[String, Int]()
    val x = new HashMap[String, Int]
    val x = HashMap[String, Int]() // factory invocation
    
    // full inference
    val x = HashMap("dog" -> 3)
    

    编辑根据要求,我添加了高阶函数案例。

    def higherOrderFunction(firstClassFunction: (Int, Int) => Int) = ...
    

    可以这样调用:

    higherOrderFunction(_ + _) // the type of the firstClassFunction is omitted
    

    但是,这不是特例。明确提到了引用的类型。下面的代码说明了一个类似的例子。

    var function: (Int, Int) => Int = null
    function = _ + _
    

    这大致相当于高阶函数的情况。

    【讨论】:

    • 有一个对这个问题非常重要的缺失案例。如果一个方法需要一个特定类型的函数,那么你可以在将函数传递给该方法时省略类型。
    【解决方案2】:

    你的第四个例子是一个方法,而不是一个函数(见this question)。您必须指定方法的参数类型。可以推断方法的返回类型,除非该方法是递归的,在这种情况下必须明确指定。

    【讨论】:

    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2016-12-03
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多