scala特殊函數定義

def name="myname"es6

若是像上面這樣定義函數fun,則使用時不能這樣使用app

val yourname = name()
<console>:15: error: not enough arguments for method apply: (index: Int)Char in class StringOps.
Unspecified value parameter index.
       val yourname = name()函數


只能val yourname = name這樣使用。只有函數定義時帶有了括號則調用時纔能有括號。這樣name其實有點像屬性。Scala做者建議,若是一個函數在邏輯上表達一種屬性的返回值,那麼在定義函數時儘可能使用不帶括號的寫法,由於這樣看上去更像一個類的屬性,而不像一個方法。因爲不帶括號的函數比帶括號的函數在使用上更嚴格,所以未來要把一個帶括號的函數定義改成不帶括號的函數定義就比較麻煩——須要先將全部帶括號的函數調用,好比name(), 通通改成不帶括號的。spa

還作了一個實驗,到如今還不明白原理:ci

  1. object WithScope {  
  2.   def withScope2(fun: =>String)={  
  3.     fun  
  4.   }  
  5.   def withScope1(fun: (String)=>String)={  
  6.     fun  
  7.   }  
  8.   def fun()={  
  9.     println("haha")  
  10.     "success"  
  11.   }  
  12.   def main(args: Array[String]): Unit = {  
  13.     withScope2{fun;println(11);"111"}  
  14.   }  
  15. }  

當我 withScope2{fun;println(11);"111"}時打印以下信息:
haha
11
res6: String = 111it

相關文章
相關標籤/搜索