Skip to content

Commit dc28bb0

Browse files
committed
add solution
1 parent 62478fe commit dc28bb0

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

core-kotlin-modules/core-kotlin-10/src/test/kotlin/com/baeldung/variableshadowing/VariableShadowingUnitTest.kt

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,79 @@ class VariableShadowingUnitTest{
8383
assertEquals(0, sum)
8484
}
8585

86+
@Test
87+
fun `solution to avoid shadowing`(){
88+
val topLevelNumber = 10 // Top-level variable
89+
90+
fun getNumber() : 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+
class Car {
100+
val speed: Int = 100
101+
102+
fun upSpeed() : 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+
fun calculateTotalPrice(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+
fun applyDiscount(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
154+
sum += newNumber
155+
}
156+
157+
assertEquals(0, sum)
158+
159+
}
160+
86161
}

0 commit comments

Comments
 (0)