Scala Call by Name && Call by Value

Scala Call by Name && Call by Value

如下scala代码,看一下这两者的区别。

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

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

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

callByValue(something())

println("====================")

callByName(something())

看一下运行结果,

E:\test-scala>scala function_called.scala
calling something
x1=1
x2=1
====================
calling something
x1=1
calling something
x2=1


Call by Value

正如其名字一样,函数调用的过程中传值,比如C 语言中的值调用,something函数返回Int 值,函数调用传值。


Call by Name

首先看 wiki 上如何解释的:In call-by-name evaluation, the arguments to a function are not evaluated( 求…的值(或数)) before the function is called — rather, they are substituted(代替,代换) directly into the function body (using capture-avoiding substitution(代替)) and then left to be evaluated whenever they appear in the function. If an argument is not used in the function body, the argument is never evaluated; if it is used several times, it is re-evaluated each time it appears. 

这段文字就很好的解释了callByName的效果。根据上边那个例子。

参考资料

http://blog.csdn.net/bobozhengsir/article/details/13023023

http://stackoverflow.com/questions/13337338/call-by-name-vs-call-by-value-in-scala-clarification-needed

http://blog.sina.com.cn/s/blog_6d27562901019oxw.html

http://stackoverflow.com/questions/6297153/what-does-code-unit-mean-in-scala

================END================

你可能感兴趣的:(Scala Call by Name && Call by Value)