Scala函数何时执行
when do Scala functions execute
在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
正如你所看到的,函数的行为就像你从函数中期望的那样。
相关文章:
- 如何检测何时执行 iframe 脚本
- AngularJS-由$scope创建的作用域何时执行$new()已删除.垃圾收集器或Angular负责处理它吗
- Javascript:Coderbyte挑战4:字母变化:帮助分析代码:这是如何大写元音的,以及何时执行else语句
- 如果另一个功能完成,则执行该功能,而不是何时
- 何时使用自动函数执行
- 何时执行与 DOM 更改相关的 JavaScript
- $.延迟:如何检测每个承诺何时执行
- 合成 JavaScript 元素何时执行
- 在执行某些 ajax 操作时,此匿名回调函数何时运行
- 如何知道回调循环的哪一次迭代以及何时执行
- 确定异步执行何时完成
- 知道.each()启动的所有异步调用何时执行完毕
- Scala函数何时执行
- 如何知道何时成功执行了多个回调,没有返回的承诺
- 无论如何,在执行entityAspect.acceptChanges之后,知道实体何时完成提交
- 是否可以检测何时执行了Firebase快照
- 检测Javascript何时完成执行
- 何时执行$.Ajax或$.Get或$.post在jQuery AJAX
- Javascript函数何时执行?PHP变量不会改变传入的参数
- 如何/何时在"For"循环被执行?Javascript