Scala中的val与Java中的const有何不同? [英] How is val in scala different from const in java?
问题描述
任何人都想详细说明scala中的val与Java中的const有何不同?
技术上有什么区别?我相信我了解C ++和Java中的 const是什么。我感觉到 val在某种意义上是有所不同和更好的,但我只是无法动弹。谢谢
Anyone care to elaborate on how val in scala is different from const in java?
What are the technical differences? I believe I understand what "const" is in c++ and java. I get the feeling that "val" is somehow different and better in some sense but I just can't put my finger on it. Thanks
推荐答案
const
在Java中没有功能-它是保留的,但实际上不能将其用于任何用途。将Java变量声明为 final
是 大致等效 。
const
in Java has no function—it's reserved but you can't actually use it for anything. Declaring a Java variable as final
is roughly equivalent.
在Scala中将变量声明为 val
具有与Java final类似的保证
-但是Scala val
实际上是方法,除非它们被声明为 private [this]
。下面是一个示例:
Declaring a variable as a val
in Scala has similar guarantees to Java final
—but Scala val
s are actually methods unless they're declared as private[this]
. Here's an example:
class Test(val x: Int, private[this] val y: Int) {
def z = y
}
这是编译后的类文件的样子:
Here's what the compiled classfile looks like:
$ javap -p Test
Compiled from "Test.scala"
public class Test {
private final int x;
private final int y;
public int x();
public int z();
public Test(int, int);
}
因此,从此示例中可以清楚地看到 private [this ] val
实际上与Scala等效于Java的 final
,因为它只是创建一个字段(没有getter方法)。但是,这是一个私有字段,所以即使不是完全相同。
So it's clear from this example that private[this] val
is actually Scala's equivalent of Java's final
in that it just creates a field (no getter method). However, it's a private field, so even that's not quite the same.
另一个有趣的事实: Scala也有一个最终
关键字! Scala的 final
的行为类似于 final
对类的工作方式在Java中-即它防止覆盖。这是另一个示例:
Another fun fact: Scala also has a final
keyword! Scala's final
behaves similarly to how final
works for classes in Java—i.e. it prevents overriding. Here's another example:
final class Test(final val x: Int, final var y: Int) { }
和生成的类:
$ javap -p Test
Compiled from "Test.scala"
public final class Test {
private final int x;
private int y;
public final int x();
public final int y();
public final void y_$eq(int);
public Test(int, int);
}
请注意最终变量
定义使getter和setter方法成为最终方法(即,您不能覆盖它们),而不是后备变量本身。
Notice that the final var
definition makes the getter and setter methods final (i.e. you can't override them), but not the backing variable itself.
这篇关于Scala中的val与Java中的const有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!