求值策略
Scala里有两种求值策略(Evaluation Strategy )
- Call By Value - 对函数实参求值,且仅求值一次
- Call By Name - 函数实参每次在函数体内被用到时都会求值
Scala通常使用Call By Value
如果函数形参类型以 => 开头,那么使用Call By Name
def foo(x: Int) =x //Call By Value
def foo(x: => Int) =x //Call By Name
求值策略的栗子(注意其区别):
def test1(x: Int,y: Int) : Int = x*x
def test2(x: =>