簡體   English   中英

使用lazy val進行名稱調用和call-by-value

[英]call-by-name and call-by-value with lazy val

我想知道一個變量傳遞的值,但是懶惰,並在Scala中按名稱傳遞一個變量。

我寫這個例子試圖表明,但我沒有,我該怎么辦?

def callByValue(x : Unit) = {
x
x
}

def callByName(x : => Unit) = {
    x
    x
}

lazy val j = {println("initializing lazy"); 0}
var i = {println("initializing"); 0}

callByName(i = i + 1)
print(i + "\n")  // "5"

callByValue(j)
print(j + "\n")  // "1"

用“5”表示,就像2,對嗎? 而“1”表示0?

這是Google面試問題嗎?

這顯示函數的閉包評估兩次:

scala> callByName {
     | println("calling")
     | i += 1
     | }
calling
calling

接着

scala> println(i)
4

那是在2之后。

HTH。

看看這是否有幫助。

  • val在定義時執行
  • lazy val執行一次但在第一次引用時
  • :=>按名稱傳遞每次在引用時執行,但不在定義時執行(將其視為函數,函數在調用/引用時執行,而不是在我們定義函數時執行),

     def callByValue(x : Unit) = { xx } def callByName(x : => Unit) = { xx } val i = {println("i"); 0}//print should happen now at time of declaration. i is 0. lazy val j = {println("j"); 0} //no print because {...} will get executed when j is referenced, not at time of definition. val k = {println("k"); 0} //same as case of i, print should happen now. K should be 0 //no special case. A val being passed like a regular function println("k test. K is val") callByValue (k) //no prints as K block is already evaluated. //passing a val to a function by name. The behavior will be same as K because i is already evaluated at time of definition. basically we are passing 0 println("i test. i is val but passed by Name."); callByName(i);//I is passed by name. Thus the block will be executed everytime it is referenced println("j test. It is passed lazy. It will be executed only once when referenced for 1st time") callByValue(j) //prints j once, assigns value 0 to j inside callByValue function. Note that because j is lazy, it the block {print j;0} is evaluated once when j was referenced for first time. It is not executed everytime j was referenced. println("test l") callByName({println("l");0});//l is passed by name. Thus the block will be executed everytime it is referenced 

    println(“再次測試l”)callByValue({println(“l”); 0}); // l按值傳遞。 因此該塊將被執行一次

產量

i <- when i was defined. val i = {println("i"); 0}
k <- when k was defined. {println("k"); 0}
k test. K is val <- no further prints of 'k' as the {println("k"); 0} has already been evaluated
i test. i is val but passed by Name. <- no furhter prints of 'i' as {println("i"); 0} is already evaluated
j test. It is passed lazy. It will be executed only once when referenced for 1st time
j <- note j is printed now instead of time of definition

test l
l <- we passed {print(l);0}. It will get executed everytime l is referenced. Thus two prints corresponding to {x;x} code of call by name
l
test l again
l <- only one print when {print(l);0} was passed by value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM