Scala函数何时执行

when do Scala functions execute

本文关键字:执行 何时 函数 Scala      更新时间:2023-09-26

在Javascript中,我可以描述这样的函数

function showString(){ console.log("this is a string") }; 

这样,在控制台中,功能和执行的功能之间有严格的区别

> function showString(){ console.log("this is a string") }; 
> showString
function showString(){ console.log("this is a string") }
> showString()
this is a string 

在Scala,我现在也在做同样的事情;

def showname() = println("this is a string")

然而,当我在控制台中运行它时,它似乎总是执行函数,而不是仅仅传递函数:

scala> def showname() = println("this is a string")
showname: ()Unit
scala> showname // I am expecting a function, not an executed function
this is a string
scala> showname()
this is a string // I am expecting an executed function

Scala处理函数的方式不同吗?我的期望错了吗?

showname实际上是一个方法,而不是一个函数,如果你想获得一个函数你可以使用下划线语法:

scala> def showname() = println("this is a string")
showname: ()Unit
scala> showname
this is a string
scala> showname _
res1: () => Unit = <function0> 

Unit返回<function0>String:

scala> res1
res2: () => Unit = <function0>
scala> res1()
this is a string

如果修改showname的签名并尝试在没有参数的情况下调用它,也可以检查它是否是一个方法:

scala> def showname(s: String) = println("this is a string")
showname: (s: String)Unit
scala> showname
<console>:9: error: missing arguments for method showname;
follow this method with `_' if you want to treat it as a partially applied function
              showname

对于函数和方法之间的差异,有一篇很棒的SO文章。

这不是函数,而是方法。这是一个功能:

val showname = () => println("this is a string")
showname
// => res0: () => Unit = <function0>
showname()
// this is a string

正如你所看到的,函数的行为就像你从函数中期望的那样。