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

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.

主站蜘蛛池模板: 牙克石市| 乌鲁木齐市| 通榆县| 门头沟区| 葫芦岛市| 苗栗市| 前郭尔| 大邑县| 湖州市| 玛多县| 德格县| 利川市| 蛟河市| 南平市| 清远市| 霸州市| 安溪县| 桐乡市| 阿荣旗| 辽宁省| 将乐县| 商城县| 北流市| 滁州市| 贵州省| 安康市| 巧家县| 开阳县| 毕节市| 长汀县| 莱州市| 甘孜县| 珲春市| 稻城县| 石台县| 嘉黎县| 威远县| 西林县| 嘉善县| 临湘市| 曲水县|