何时执行Scala函数

时间:2014-08-29 13:03:36

标签: 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处理功能有何不同?我的期望是错的吗?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

这不是一个功能,这是一种方法。这是一个功能:

val showname = () => println("this is a string")

showname
// => res0: () => Unit = <function0>

showname()
// this is a string

正如您所看到的,该函数的行为与您从函数中所期望的一样。

相关问题