Scala 中的表达式和语句有什么区别 [英] What is the difference between Expressions and Statements in Scala
问题描述
我是 Scala 世界的新手,想知道表达式和语句之间有什么区别,以及为什么将 if-else 用于表达式而不是语句.如果有办法在 if-else 中使用语句?
I'm new in Scala world and want to know what is the difference between Expressions and Statements and Why if-else is used for expression, not statements. And if there is a way to use statement in if-else?
推荐答案
EDIT:正如@Jörg W Mittag 在评论中指出的那样,这个答案实际上是错误的:声明确实存在于 Scala 规范中:
EDIT: As pointed out by @Jörg W Mittag in the comments, this answer is in fact wrong: statements do exist in the Scala spec:
语句作为块和模板的一部分出现.语句可以是导入、定义或表达式,也可以为空.
Statements occur as parts of blocks and templates. A statement can be an import, a definition or an expression, or it can be empty.
我保留原始答案,因为我认为它作为对 OP 问题的实际答案仍然很有价值.
I leave the original answer, as I think it is still valuable as a practical answer to the OP's question.
原始答案
迂腐地说,Scala 中没有声明这样的东西.有定义(如def
和class
)和表达式.在其他语言中被称为语句的一切都只是一个表达式.
Pedantically speaking, there is no such thing as a statement in Scala. There are definitions (such as def
and class
) and expressions. Everything that would be called a statement in other languages is just an expression.
例如,许多人会调用以下打印到控制台的行",一个语句:
For example, many people would call the following "line", which prints to the console, a statement:
println("hello")
在 Scala 中,这是一个表达式.比如可以赋值给一个值:
In Scala, this is an expression. For example, it can be assigned to a value:
val x = println("hello")
在这种情况下,x
被分配了类型 Unit
的值 ()
(读作 unit
).
In this case, x
is assigned the value ()
(pronounced unit
) of type Unit
.
除了理论"之外,通常的做法是调用始终返回 ()
语句的表达式.这意味着上面的 println("hello")
也可以看作是一个语句.
"Theory" aside, it is common practice to call an expression that always returns ()
a statement. Which means that the above println("hello")
can also be considered as a statement.
现在让我们回到if/else
.由于一切都是表达式,所以这个 if/else
是一个表达式:
Let us now come back to if/else
. Since everything is an expression, this if/else
is an expression:
if (cond) 3 else 5
不过如此
if (cond)
println("hello")
else
println("bye")
在后一个例子中,if/else
总是返回 ()
(因为 println
都返回 ()
),因此您可以将此 if/else
称为语句.
In the latter example, though, the if/else
always returns ()
(because both println
s return ()
), and you can therefore call this if/else
a statement.
这篇关于Scala 中的表达式和语句有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!