本文介绍了Scala 中的一切都是函数、表达式或对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我很困惑.

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

I thought everything is expression because the statement returns a value. But I also heard that everything is an object in scala.

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

What is it in reality? Why did scala choose to do it one way or the other? What does that mean to a scala developer?

推荐答案

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

There are things that don't have values, but for the most part, this is correct. That means that we can basically drop the distinction between "statement" and "expression" in Scala.

然而,术语返回值"并不合适.我们说一切都评估"为一个值.

The term "returns a value" is not quite fitting, however. We say everything "evaluates" to a value.

但我也听说在 Scala 中一切都是对象.

这与前面的语句完全不矛盾:) 这只是意味着每个可能的 value 都是一个对象(所以每个表达式的计算结果都是一个对象).顺便说一下,函数作为 Scala 中的一等公民,也是对象.

That doesn't contradict the previous statement at all :) It just means that every possible value is an object (so every expression evaluates to an object). By the way, functions, as first-class citizens in Scala, are objects, too.

为什么 Scala 会选择这样或那样的方式?

需要注意的是,这实际上是 Java 方式的概括,其中语句和表达式是不同的东西,并不是所有的东西都是对象.您可以将每一段 Java 代码转换为 Scala,而无需进行大量修改,但反之则不然.所以这个设计决定实际上让 Scala 在简洁性和表达性方面更强大.

It has to be noted that this is in fact a generalization of the Java way, where statements and expressions are distinct things and not everything is an object. You can translate every piece of Java code to Scala without a lot of adaptions, but not the other way round. So this design decision makes Scala is in fact more powerful in terms of conciseness and expressiveness.

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

例如,这意味着:

  • 您通常不需要return,因为您可以将返回值作为方法中的最后一个表达式
  • 您可以利用 ifcase 是表达式这一事实来缩短您的代码
  • You often don't need return, because you can just put the return value as the last expression in a method
  • You can exploit the fact that if and case are expressions to make your code shorter

一个例子是:

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

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

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

We can also assign the value of such a compound expression to a variable:

val str = value match {
            case Some(x) => "Result: " + x
            case None    => "Error!"
          }

这篇关于Scala 中的一切都是函数、表达式或对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:42