@@ -10,26 +10,28 @@ next-page: unified-types
10
10
previous-page : tour-of-scala
11
11
---
12
12
13
- ## Values and Variables
13
+ In this page, we will cover basics of Scala.
14
14
15
- You can define values with ` val ` keyword.
15
+ ## Variables
16
+
17
+ You can define variables with ` var ` keyword.
16
18
17
19
```
18
- val x = 1 + 1
20
+ var x = 1 + 1
21
+ x += 1
19
22
```
20
23
21
- When defined with ` val ` , you cannot mutate the binding .
24
+ Often, you want your variables to be immutable. You can use ` val ` keyword in that case .
22
25
23
26
```
24
27
val x = 1 + 1
25
- x += 1 // This does not compile because you are mutating values defined with "val" keyword
28
+ x += 1 // This does not compile because you declared the variable with "val" keyword
26
29
```
27
30
28
- You can use ` var ` instead to make it variable, allowing mutation .
31
+ Type of variables can be inferred, but you can also explicitly state type like below .
29
32
30
33
```
31
- var x = 1 + 1
32
- x += 1
34
+ val x: Int = 1 + 1
33
35
```
34
36
35
37
## Functions
@@ -75,7 +77,7 @@ We will cover classes in depth [later](classes.md).
75
77
76
78
## Traits
77
79
78
- Traits are used to define object types by specifying the signature of fields and methods.
80
+ Traits define types as signature of fields and methods.
79
81
80
82
You can define traits with ` trait ` keyword.
81
83
@@ -146,7 +148,7 @@ println(point == yetAnotherPoint) // false
146
148
147
149
Case classes are immutable by default, but it also provides ` copy ` method so that you can easily create another instance of the class while reusing the values from exiting instances.
148
150
149
- Using ` copy ` method, you can write the above code like below.
151
+ Using ` copy ` method, you can also write the above code like below.
150
152
151
153
```
152
154
val point = Point(1, 2)
@@ -156,7 +158,7 @@ println(point == anotherPoint) // true
156
158
println(point == yetAnotherPoint) // false
157
159
```
158
160
159
- There are many other features you get out-of-box by using case classes. We will cover them [ later] ( case-classes.md ) .
161
+ There are many other features you get out-of-the- box by using case classes. We will cover them in depth [ later] ( case-classes.md ) .
160
162
161
163
## Singleton Objects
162
164
@@ -173,6 +175,15 @@ object IdFactory {
173
175
}
174
176
```
175
177
178
+ You can access singleton objects just by referring its name.
179
+
180
+ ```
181
+ val newId: Int = IdFactory.create()
182
+ println(newId) // 1
183
+ val newerId: Int = IdFactory.create()
184
+ println(newerId) // 2
185
+ ```
186
+
176
187
We will cover singleton objects in depth [ later] ( singleton-objects.md ) .
177
188
178
189
## Main Method
0 commit comments