2014-08-29 49 views
1

在Javascript中我可以描述像這樣何時Scala的功能執行

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的處理功能不同?我的期望錯了嗎?

回答

4

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 

對於函數和方法之間的區別,有this great SO post

+0

我認爲*函數對象*是一個更好的名字,因爲你在_應用之後得到的東西(雖然,不理想,因爲scala中的對象帶有另一個含義 - 單例)。 – 2014-08-29 13:51:38

+0

@ om-nom-nom我明白你的觀點,但我覺得說實話很混亂,我也從來沒有讀過這種命名方式(或者我沒有注意到),但我始終堅持使用它。 – 2014-08-29 14:17:26

+0

好的:-)我只提出了替代方案。 *我從來沒有讀過這種命名*,[它比較流行](https://www.google.com/search?q=「function + object」+ scala&oq =「function + object」+ scala)。 – 2014-08-29 14:29:42

1

這不是一個函數,這是一種方法。這是一個功能:

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

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

showname() 
// this is a string 

而且正如你所看到的,函數的行爲就像你期望的那樣。