官术网_书友最值得收藏!

Declaring variables

In Scala, a variable can be declared using val or var. A val is immutable, which means you can never change its value. A var is mutable. It is not mandatory to declare the type of the variable. If you do not declare it, Scala will infer it for you.

Let's define some immutable variables:

In all the following code examples, you only need to type the code that is after the Scala Command Prompt, and hit Ctrl + Enter or cmd + return to evaluate. We show the result of the evaluation underneath the prompt, as it would appear on your screen.
scala> val x = 1 + 1
x: Int = 2

scala> val y: Int = 1 + 1
y: Int = 2

In both cases, the type of the variable is Int. The type of x was inferred by the compiler to be Int. The type of y was explicitly specified with : Int after the name of the variable.

We can define a mutable variable and modify it as follows:

scala> var x = 1
x: Int = 1

scala> x = 2
x: Int = 2

It is a good practice to use val in most situations. Whenever I see a val declared, I know that its content will never change subsequently. It helps to reason about a program, especially when multiple threads are running. You can share an immutable variable across multiple threads without fearing that one thread might see a different value at some point. Whenever you see a Scala program using var, it should make you raise an eyebrow: the programmer should have a good reason to use a mutable variable, and it should be documented.

If we attempt to modify a val, the compiler will raise an error message:

scala> val y = 1
y: Int = 1

scala> y = 2
<console>:12: error: reassignment to val
y = 2
^

This is a good thing: the compiler helps us make sure that no piece of code can ever modify a val.

主站蜘蛛池模板: 综艺| 华池县| 雷山县| 尤溪县| 军事| 上高县| 出国| 永定县| 多伦县| 渑池县| 同仁县| 通州区| 永修县| 五华县| 米脂县| 康乐县| 疏勒县| 抚松县| 弋阳县| 万安县| 安陆市| 耒阳市| 屏南县| 偏关县| 体育| 儋州市| 麻栗坡县| 定边县| 宜黄县| 屏东县| 剑川县| 汾阳市| 广南县| 铜鼓县| 元朗区| 沙洋县| 都兰县| 政和县| 阿拉尔市| 永城市| 天水市|