Scala 中 def 和 val 的区别 [英] Difference between def and val in Scala
问题描述
循环定义如下:
def loop : Boolean = loop
当 x 定义为:def x = loop
时,控制台会显示x: Boolean".
When x is defined as: def x = loop
then "x: Boolean" is shown in console.
和
当 x 定义为:val x = loop
则进入无限循环
When x is defined as: val x = loop
then it goes to infinite loop
我知道 def 使用的是按名称调用,而 val 使用的是按值调用.尽管上面定义的关于循环的这一点不是很清楚.
I know def is using call by-name and val is using call by-value. Even though this point about loop defined above is not much clear.
推荐答案
def
不评估作业的右侧.就像
def
doesn't evaluate the right-hand side of the assignment. Just like
def f(x : Int) = x + 2
不(在这种情况下逻辑上不能)评估 f
的任何内容,只是定义函数 f
的含义,既不是 def 循环:Boolean = loop
或 def x = loop
评估任何东西.您只是定义了一个要在其他时间执行的函数.
doesn't (in this case logically can't) evaluate f
of anything, just defines what the function f
, means, neither def loop : Boolean = loop
nor def x = loop
evaluate anything. You are just defining a function to be executed at some other point.
但是 val
确实需要对赋值的右侧进行评估.所以 val x = loop
尝试执行右侧的表达式.但是,尝试计算 loop
永远不会终止,因为 loop
是一个无限循环.
But val
s do require the right-hand side of the assignment to be evaluated. So val x = loop
tries to execute the expression on the right-hand side. Trying to evaluate loop
never terminates, though, since loop
is an infinite loop.
这篇关于Scala 中 def 和 val 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!