8

我很困惑。

我认为一切都是表达式,因为语句返回一个值。但我也听说在 scala 中一切都是对象。

现实中是什么?为什么 scala 选择以一种方式或另一种方式来做呢?这对 Scala 开发人员意味着什么?

4

3 回答 3

16

我认为一切都是表达式,因为语句返回一个值。

有些东西没有价值,但在大多数情况下,这是正确的。这意味着我们基本上可以放弃 Scala 中“语句”和“表达式”之间的区别。

然而,术语“返回一个值”不太合适。我们说一切都“评估”为一个价值。

但我也听说在 scala 中一切都是对象。

这根本不与前面的陈述相矛盾:) 它只是意味着每个可能的都是一个对象(因此每个表达式都计算为一个对象)。顺便说一句,函数作为 Scala 中的一等公民,也是对象。

为什么 scala 选择以一种方式或另一种方式来做呢?

需要注意的是,这实际上是 Java 方式的概括,其中语句和表达式是不同的事物,并非所有事物都是对象。您可以将每段 Java 代码翻译成 Scala 而不需要进行大量调整,但反过来就不行。所以这个设计决策使得Scala实际上在简洁性和表达性方面更加强大

这对 Scala 开发人员意味着什么?

例如,这意味着:

  • 您通常不需要return,因为您可以将返回值作为方法中的最后一个表达式
  • if您可以利用and是表达式的事实case来使您的代码更短

一个例子是:

def mymethod(x: Int) = if (x > 2) "yay!" else "too low!"

// ...
println(mymethod(10))  // => prints "yay!"
println(mymethod(0))   // => prints "too low!"

我们还可以将这样一个复合表达式的值赋给一个变量:

val str = value match {
            case Some(x) => "Result: " + x
            case None    => "Error!"
          }
于 2012-04-05T03:56:40.060 回答
8

The distinction here is that the assertion "everything is a expression" is being made about blocks of code, whereas "everything is an object" is being made about the values in your program.


Blocks of Code

In the Java language, there are both expressions and statements. That is, any "block" of code is either an expression or a statement;

//the if-else-block is a statement whilst (x == 4) is an expression
if (x == 4) {
    foo();
}
else {
    bar();
}

Expressions have a type; statements do not; statements are invoked purely for their side-effects.

In scala, every block of code is an expression; that is, it has a type:

if (x == 4) foo else bar //has the type lub of foo and bar

This is extremely important! I cannot stress this enough; it's one of the things which makes scala a pleasure to work with because I can assign a value to an expression.

val x = if (x == 4) foo else bar

Values

By value, I mean something that we might reference in the program:

int i = foo(); //i is a reference to a value
java.util.TimeUnit.SECONDS;

In Java, the i above is not an object - it is a primitive. Furthermore I can access the field SECONDS of TimeUnit, but TimeUnit is not an object either; it is a static (for want of a better phrase). In scala:

val j = 4
Map.empty

As far as the language is concerned, j is an object (and I may dispatch methods to it), as is Map - the module (or companion object) for the type scala.collection.immutable.Map.

于 2012-04-05T13:34:22.240 回答
6

scala中的一切都是函数、表达式或对象吗?

没有。

有些东西不是对象。例如类、方法。

有些东西不是表达。egclass Foo { }是一个语句,不计算任何值。(这与上面的基本相同。)

有些东西不是函数。我不需要为此提及任何示例,因为在任何 Scala 代码中都会看到很多。

换句话说,“一切都是 X”只不过是一种推销(在 Scala 的情况下)。

于 2012-04-05T13:57:36.173 回答