在 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>
返回 <function0>
来自 Unit
至 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
对于函数和方法之间的差异,有 this great SO post .
关于javascript - Scala函数什么时候执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568881/