使用函数代替方法,即使使用`def`

问题描述 投票:0回答:1

为什么,即使使用def,以下语法也会创建函数而不是方法吗?

def hello = (a: Int) => {
    println(a)
}

此类型

hello: Int => Unit

[一个人可以在其上使用.apply(),就像一个人可以对函数进行操作(但不能对方法进行处理:]

hello.apply(5)

虽然这其他三种语法(我确定还有其他1000种表达同一事物的方式略有不同)产生方法:

// def name (args) : return_type = body
def hello(a:Int): Unit = {
    println(a)
}
// with type inference for return type
def hello(a: Int) = {
    println(a)
}
// without the '='
def hello(a: Int) {
    println(a)
}

(以上类型为hello: (a: Int)Unit


奖励问题:第一个hello的类型为hello: Int => Unit。这似乎与通过定义函数hello: Int => Unit = <function1>所获得的结果有所不同。它们真的不同吗?

scala function methods syntax
1个回答
1
投票

否,它是返回Int => Unit函数的方法。调用方法时,您会得到此hello: Int => Unit = <function1>,您好有scala 2.12版。

具有高于Scala版本的版本,您将获得类似Int => Unit = $$Lambda$1047/1845297077@184fb68d而不是hello: Int => Unit = <function1>的类型>

© www.soinside.com 2019 - 2024. All rights reserved.