在Scala中,调用函数有两种形式:Call by value(按值调用)和call by name(按名称调用)。若是call by value,会先计算参数的值,然后再传递给被调用的函数;若是call by name,参数会到实际使用的时候才计算。例如:
vallogEnable=falsedeflog(msg:String)=if(logEnable)println(msg)valMSG="programing is running"log(MSG+1/0)
此时的log函数是call by value。因此在调用log函数时,会先计算传入的参数,此时会计算MSG + 1/0。由于表达式中有0作为被除数,因此会抛出异常:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main$.main(scala-script352098905369979205.scala:16)
at Main.main(scala-script352098905369979205.scala)
exit value is 1
Program exited.