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
+75Lines changed: 75 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -83,4 +83,79 @@ class VariableShadowingUnitTest{
83
83
assertEquals(0, sum)
84
84
}
85
85
86
+
@Test
87
+
fun`solution to avoid shadowing`(){
88
+
val topLevelNumber =10// Top-level variable
89
+
90
+
fungetNumber() : Int {
91
+
val localNumber =20// Local variable without shadowing
92
+
return localNumber
93
+
}
94
+
95
+
assertEquals(20, getNumber())
96
+
assertEquals(10, topLevelNumber)
97
+
98
+
// in class member
99
+
classCar {
100
+
val speed:Int=100
101
+
102
+
funupSpeed() : Int {
103
+
val newSpeed = speed *2// Using a new variable name to avoid shadowing
104
+
return newSpeed
105
+
}
106
+
}
107
+
108
+
assertEquals(100, Car().speed)
109
+
assertEquals(200, Car().upSpeed())
110
+
111
+
funcalculateTotalPrice(discount:Int) {
112
+
val updatedDiscount = discount +10// Using a new variable name to avoid shadowing
113
+
assertEquals(30, updatedDiscount)
114
+
115
+
val price =100// local variable
116
+
val discountRate =0.1
117
+
118
+
funapplyDiscount(price:Int): Double { // Nested function with parameter named 'price'
119
+
val updatedDiscountRate =0.2// Using a new variable name to avoid shadowing
120
+
return price * (1- updatedDiscountRate) // 'price' here refers to the parameter, not the outer variable
121
+
}
122
+
123
+
assertEquals(80.0, applyDiscount(price))
124
+
}
125
+
126
+
calculateTotalPrice(20)
127
+
128
+
val numbers =listOf(1, 2, 3, 4, 5)
129
+
130
+
// in loop
131
+
for (number in numbers) {
132
+
val doubledNumber = number *2
133
+
val newNumber = number *2// Using a new variable name to avoid shadowing
134
+
135
+
assertEquals(doubledNumber, newNumber)
136
+
}
137
+
138
+
// in extension
139
+
assertEquals(15, numbers.sum())
140
+
141
+
fun List<Int>.sum(): Int { // shadowing built-in function sum()
142
+
var sum =0
143
+
this.forEach { sum += it *2 }
144
+
return sum
145
+
}
146
+
147
+
assertEquals(30, numbers.sum())
148
+
149
+
// in lambda
150
+
var sum =0
151
+
152
+
numbers.forEach { number ->
153
+
val newNumber =0// Using a new variable name to avoid shadowing
0 commit comments