- Learning Scala Programming
- Vikash Sharma
- 478字
- 2021-06-30 19:07:48
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.
- Java高并發核心編程(卷2):多線程、鎖、JMM、JUC、高并發設計模式
- Android 9 Development Cookbook(Third Edition)
- Selenium Design Patterns and Best Practices
- VSTO開發入門教程
- UML+OOPC嵌入式C語言開發精講
- 64位匯編語言的編程藝術
- Monitoring Elasticsearch
- Hands-On Enterprise Automation with Python.
- Functional Kotlin
- PLC編程與調試技術(松下系列)
- BIM概論及Revit精講
- C++新經典
- 好好學Java:從零基礎到項目實戰
- Python預測分析實戰
- Mastering OAuth 2.0