1. 程式人生 > >scala 傳值引數和傳名引數 ():=>和:=>

scala 傳值引數和傳名引數 ():=>和:=>

傳值引數程式碼示例:

def test1(code: ()=>Unit){
    println("start")
    code() //要想呼叫傳入的程式碼塊,必須寫成code(),否則不會呼叫。  
    println("end")
  }
  test1 {//此程式碼塊,傳入後立即執行。  
    println("1111")
    ()=>{println("2222")}
  }
  輸出內容:
  1111
  start
  2222
  end   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

傳名引數的示例:

def test(code : => Unit){  
  println("start"
)
code // 這行才會呼叫傳入的程式碼塊,寫成code()亦可 println("end") } test{// 此處的程式碼塊不會馬上被呼叫 println("1111") println("2222") } 輸出結果: start 1111 2222 end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

因為scala建議如果函式的引數只有一個,可以考慮使用{}代替(),因此test和test1的呼叫都是{},又因為test的引數是傳名引數函式,因此傳入的引數是不會被執行的,而test1的引數是傳值引數,因此需要先計算引數的值,然後再傳入test1的方法體中,恰好test1傳入引數的計算結果是一個匿名函式,因此可以執行,如果test1的傳入引數的計算結果不是函式,那麼就會報錯。所以test和test1的呼叫,輸出結果有所不同。 
文章參考 : 
=>Unti和:=>的區別

http://scalagroup.group.iteye.com/group/topic/26303, 當然本片文章的內容介紹的是:=>和():=>的區別。 

而=>Unit和:=>的區別是,() => Unit是一個函式,=> Unit 是一個執行結果為Unit的表示式。

如下是stackoverflow的回答

The example you have given only uses call-by-value, so I will give a new, simpler, example that shows the difference.

First, let's assume we have a function with a side-effect. This function prints something out and then returns an Int

.

def something()={
  println("calling something")1// return value}

Now we are going to define two function that accept Int arguments that are exactly the same except that one takes the argument in a call-by-value style (x: Int) and the other in a call-by-name style (x: => Int).

def callByValue(x:Int)={
  println("x1="+ x)
  println("x2="+ x)}def callByName(x:=>Int)={
  println("x1="+ x)
  println("x2="+ x)}

Now what happens when we call them with our side-effecting function?

scala> callByValue(something())
calling something
x1=1
x2=1

scala> callByName(something())
calling something
x1=1
calling something
x2=1

So you can see that in the call-by-value version, the side-effect of the passed-in function call (something()) only happened once. However, in the call-by-name version, the side-effect happened twice.

This is because call-by-value functions compute the passed-in expression's value before calling the function, thus the same value is accessed every time. However, call-by-name functions recomputethe passed-in expression's value every time it is accessed