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

Vals and vars

While writing our Scala programs, we can define our member fields using either val or var keywords. When we use a val keyword to assign a value to any attribute, it becomes a value. We're not allowed to change that value in the course of our program. So a val declaration is used to allow only immutable data binding to an attribute. Let's take an example:

scala> val a = 10
a: Int = 10

Here, we have used a val keyword with an attribute named a, and assigned it a value 10. Furthermore, if we try to change that value, the Scala compiler will give an error saying: reassignment to val:

scala> a = 12
<console>:12: error: reassignment to val
a = 12

Scala recommends use of val as much as possible to support immutability. But if an attribute's value is going to change in the course of our program, we can use the var declaration:

scala> var b = 10
b: Int = 10

When we define an attribute using a var keyword, we're allowed to change its value. The var keyword here stands for variable, which may vary over time:

scala> b = 12
b: Int = 12

If you take a closer look at our declaration of value a, you will find that we're not providing the type information anywhere, but still the Scala interpreter is able to infer the type of defined value, which in our case is an integer. That happens because of the Scala compiler's type inference characteristic. We'll learn about Scala's type inference later on in this chapter. Scala's compiler is able to infer the type of declared value. So it's up to the programmer if he/she wants to explicitly give type information for good readability of the code, or let Scala do this job for him/her. In Scala, we can explicitly give types after the attribute's name:

scala> val a: String = "I can be inferred."
a: String = I can be inferred.

This is a bit different to how we declare fields in Java. First, we use a val or var  keyword , then we give its type, and then give a literal value. Here, it's a String literal. When we explicitly define type information for an attribute, then the value we give to it should justify to the type specified:

scala> val a: Int = "12"
<console>:11: error: type mismatch;
found : String("12")
required: Int
val a: Int = "12"

The preceding code is not going to work for us, because the type specified is Int, and the literal bound to our attribute is a String, and as expected, Scala gifted an error saying type mismatch. Now that we know that the bound value to our attribute is a literal, I think we're ready to discuss literals in Scala.

主站蜘蛛池模板: 香港| 鹤庆县| 临桂县| 宣城市| 赫章县| 南川市| 潮州市| 湖口县| 巴林左旗| 枣强县| 巴马| 溆浦县| 溧阳市| 镇沅| 略阳县| 湄潭县| 澄迈县| 叶城县| 黄石市| 中阳县| 萨嘎县| 安吉县| 伊宁县| 本溪市| 隆回县| 阿克苏市| 乐平市| 文山县| 大宁县| 永顺县| 新津县| 塔城市| 穆棱市| 桐乡市| 长乐市| 五河县| 定陶县| 兰考县| 阳信县| 铜鼓县| 平度市|