【问题标题】:Functions and function literals in scalascala 中的函数和函数字面量
【发布时间】:2016-10-19 14:31:56
【问题描述】:

我是 Scala 新手。请说出两者的区别

    def fun( t: Int => Int):Unit = {

    def fun(t: =>Int):Unit {

    def fun(t:=>Int):Unit { (without space b/w ":" and "=>"))

【问题讨论】:

    标签: scala function literals function-literal


    【解决方案1】:

    def fun( t: Int => Int):Unit 是一个采用单个参数t 的方法。它的类型Int => Int 是一个接受Int 并返回Int 的函数。但是fun的返回类型是Unit

    def fun(t: =>Int):Unit 是一个接受call by name 参数t 的方法。同样,这个方法的返回类型是Unit

    也见What is "Call By Name"?

    第二种和第三种方法没有区别。

    【讨论】:

    • 感谢您的回答。但是“def fun(t: Int => Int):Unit”也按名称调用吗?
    • 否,因为 => 是按名称参数调用的前缀。您提到的情况并非如此。
    • 很抱歉,您能详细说明一下吗?当我使用 def fun(t: Int => Int):Unit 运行代码并在 fun 中传递一个函数时,只有当我使用变量“t”时才会调用该函数。那么,这不是点名吗?
    • 好吧,您应用 IntInt => Int 以调用该函数。但是,在按名称调用示例中,即 def fun(t: => Int)t 仅在调用时以及每次调用时才会被评估。示例:def fun(t: => Int): Int = t + t,并调用它:fun( {println("calling fun"); 42} ),观察calling fun 将打印两次,并返回84
    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多