File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ after swap: (2, 4)
2
+ after swap: (2, 4)
3
+ after swap: (2, 4)
4
+ load 1
5
+ load 2
6
+ load 2
7
+ load 4 from 2
8
+ load 1
9
+ load 2 from 1
10
+ store 4 to 1
11
+ store 2 to 2
12
+ after swap: (4, 2)
Original file line number Diff line number Diff line change
1
+ object Test :
2
+
3
+ class Container [T ](val id : Int , var x : T ):
4
+
5
+ def y : T =
6
+ println(s " load ${x} from ${id}" )
7
+ x
8
+
9
+ def y_= (newValue : T ): Unit =
10
+ println(s " store ${newValue} to ${id}" )
11
+ this .x_=(newValue)
12
+
13
+ def main (args : Array [String ]): Unit =
14
+ // simple swap
15
+ var x1 = 4
16
+ var x2 = 2
17
+ (x1, x2) = (x2, x1)
18
+ println(s " after swap: ( ${x1}, ${x2}) " )
19
+
20
+ // swap in a container
21
+ val a = Array (4 , 2 )
22
+ (a(0 ), a(1 )) = (a(1 ), a(0 ))
23
+ println(s " after swap: ( ${a(0 )}, ${a(1 )}) " )
24
+
25
+ // swap fields with effectless left-hand sides
26
+ var c1 = Container (1 , 4 )
27
+ var c2 = Container (2 , 2 )
28
+ (c1.x, c2.x) = (c2.x, c1.x)
29
+ println(s " after swap: ( ${c1.x}, ${c2.x}) " )
30
+
31
+ // swap fields with side effectful left-hand sides
32
+ def f (n : Int ): Container [Int ] =
33
+ println(s " load ${n}" )
34
+ n match
35
+ case 1 => c1
36
+ case 2 => c2
37
+ (f(1 ).y, f(2 ).y) = (f(2 ).y, f(1 ).y)
38
+ println(s " after swap: ( ${c1.x}, ${c2.x}) " )
You can’t perform that action at this time.
0 commit comments