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

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.

主站蜘蛛池模板: 贺兰县| 大丰市| 建德市| 石泉县| 泾川县| 平乐县| 宜州市| 盐城市| 措勤县| 汝南县| 淮南市| 东明县| 卓资县| 郑州市| 阳城县| 崇州市| 饶阳县| 临泽县| 诸城市| 且末县| 高碑店市| 连城县| 天柱县| 临沂市| 左贡县| 奇台县| 寻甸| 泰宁县| 南开区| 江源县| 昔阳县| 仙游县| 平遥县| 曲阳县| 科技| 台东县| 台江县| 兖州市| 冕宁县| 都匀市| 固始县|