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: core-kotlin-modules/core-kotlin-10/src/test/kotlin/com/baeldung/variableshadowing/VariableShadowingUnitTest.kt
+21-10Lines changed: 21 additions & 10 deletions
Original file line number
Diff line number
Diff line change
@@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test
8
8
classVariableShadowingUnitTest{
9
9
10
10
@Test
11
-
fun`test variable shadowing`(){
11
+
fun`Top-level variable shadowing`(){
12
12
val number =10// Top-level variable
13
13
14
14
funupNumber() : Int { // top-level function
@@ -18,8 +18,10 @@ class VariableShadowingUnitTest{
18
18
19
19
assertEquals(20, upNumber())
20
20
assertEquals(10, number)
21
+
}
21
22
22
-
// shadowing class member
23
+
@Test
24
+
fun`shadowing class member`(){
23
25
classCar {
24
26
val speed:Int=100
25
27
@@ -31,8 +33,10 @@ class VariableShadowingUnitTest{
31
33
32
34
assertEquals(100, Car().speed)
33
35
assertEquals(200, Car().upSpeed())
36
+
}
34
37
35
-
38
+
@Test
39
+
fun`local variable shadowing`(){
36
40
funcalculateTotalPrice(discount:Int) {
37
41
val discount = discount +10// Shadowing the parameter 'discount'
38
42
assertEquals(30, discount)
@@ -49,16 +53,23 @@ class VariableShadowingUnitTest{
49
53
}
50
54
51
55
calculateTotalPrice(20)
56
+
}
57
+
52
58
59
+
@Test
60
+
fun`shadowing in loop`(){
53
61
val numbers =listOf(1, 2, 3, 4, 5)
54
62
55
63
// shadowing in loop
56
64
for (number in numbers) {
57
65
val number = number *2// Shadowing the loop variable 'number'
58
66
}
67
+
}
59
68
69
+
@Test
70
+
fun`shadowing in extension`(){
71
+
val numbers =listOf(1, 2, 3, 4, 5)
60
72
61
-
// shadowing in extension
62
73
assertEquals(15, numbers.sum())
63
74
64
75
fun List<Int>.sum(): Int { // shadowing built-in function sum()
@@ -68,8 +79,12 @@ class VariableShadowingUnitTest{
68
79
}
69
80
70
81
assertEquals(30, numbers.sum())
82
+
}
83
+
84
+
@Test
85
+
fun`shadowing in lambda`(){
86
+
val numbers =listOf(1, 2, 3, 4, 5)
71
87
72
-
// shadowing in lambda
73
88
var sum =0
74
89
75
90
numbers.forEach { number ->
@@ -84,6 +99,7 @@ class VariableShadowingUnitTest{
84
99
}
85
100
}
86
101
102
+
87
103
@Test
88
104
fun`solution to avoid shadowing`(){
89
105
val topLevelNumber =10// Top-level variable
@@ -121,11 +137,6 @@ class VariableShadowingUnitTest{
121
137
val price =100// local variable
122
138
val discountRate =0.1
123
139
124
-
// fun applyDiscount(price: Int): Double {
125
-
// val innerDiscountRate = 0.2
126
-
// return price * (1 - discountRate)
127
-
// }
128
-
129
140
funapplyDiscount(price:Int): Double {
130
141
return price * (1- discountRate) // Use the outer discountRate directly
0 commit comments