javascript - Scala函数什么时候执行

标签 javascript function scala

在 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>来自 UnitString :

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/

相关文章:

scala - Scala 中柯里化(Currying)的好处

javascript - 构建桌面 Facebook 应用程序

javascript - "slc start"是怎么判断应该加载哪个js的呢?

javascript - 如何在同一转换中使用另一个 javascript 中的一个 javascript 中的变量?

javascript - 在 "microseconds"中设置javascript函数的时间间隔

scala - 连接数百个 RxScala Observables(每个都有数百万个事件要发出)的有效方法?

scala - 如何在 x :Myclass => Boolean to get the conjunction? 的列表中使用左折叠

javascript - 如果为 NULL,则更改数组文本框的 bgcolor

Python:缩进错误

c - 如何将 3d 指针数组传递给 c 中的函数?