You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: tutorials/FAQ/initialization-order.md
+14-5Lines changed: 14 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -7,7 +7,10 @@ disqus: true
7
7
partof: FAQ
8
8
num: 9
9
9
---
10
-
Consider the following.
10
+
11
+
## Example
12
+
To understand the problem, let's pick the following concrete example.
13
+
11
14
```scala
12
15
abstractclassA {
13
16
valx1:String
@@ -25,12 +28,18 @@ class C extends B {
25
28
26
29
println("C: "+ x1 +", "+ x2)
27
30
}
28
-
// scala> new C
29
-
// A: null, null
30
-
// B: hello, null
31
-
// C: hello, dad
32
31
```
32
+
Let's observe the initialization order through the Scala REPL:
33
+
```
34
+
scala> new C
35
+
A: null, null
36
+
B: hello, null
37
+
C: hello, dad
38
+
```
39
+
40
+
Only when we get to the constructor of `C` are both `x1` and `x2` initialized. Therefore, constructors of `A` and `B` risk running into `NullPointerException`s.
33
41
42
+
## Explanation
34
43
A 'strict' or 'eager' val is one which is not marked lazy.
35
44
36
45
In the absence of "early definitions" (see below), initialization of strict vals is done in the following order.
0 commit comments