Call by Value(default,透過x: Int的方式設定):呼叫函數的時候一併將值讀入。
其實這兩種方式都不會影響到值,而是發生在值以外的side-effect。直接看範例比較快,這次的範例參考以下網址:http://stackoverflow.com/questions/13337338/call-by-name-vs-call-by-value-in-scala-clarification-needed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def test() = { | |
println("testing...") | |
1 // return value | |
} | |
def callByValue(x: Int) = { | |
println("x1="+x) | |
println("x2="+x) | |
} | |
def callByName(x: Int) = { | |
println("x1="+x) | |
println("x2="+x) | |
} | |
//call function | |
scala> callByValue(test()) | |
testing | |
x1=1 | |
x2=1 | |
scala> callByName(test()) | |
testing | |
x1=1 | |
testing | |
x2=1 | |
寫程式如果在設定參數時注意一下囉,感覺可以用call by name的特性來製造簡單的遞迴~
修正一下程式碼,gist不知道為什麼不讓我改
回覆刪除def callByName(x:=> Int) = {
println("x1="+x)
println("x2="+x)
}