1
- @file:Suppress(" UNUSED_PARAMETER " , " UNUSED_VARIABLE" , " UNUSED_ANONYMOUS_PARAMETER" )
1
+ @file:Suppress(" UNUSED_VARIABLE" , " UNUSED_ANONYMOUS_PARAMETER" )
2
2
3
3
package com.baeldung.variableshadowing
4
4
@@ -34,14 +34,14 @@ class VariableShadowingUnitTest{
34
34
35
35
36
36
fun calculateTotalPrice (discount : Int ) {
37
- val discount = 10 // Shadowing the parameter 'discount'
38
- assertEquals(10 , discount)
37
+ val discount = discount + 10 // Shadowing the parameter 'discount'
38
+ assertEquals(30 , discount)
39
39
40
40
val price = 100 // local variable
41
41
val discountRate = 0.1
42
42
43
43
fun applyDiscount (price : Int ): Double { // Nested function with parameter named 'price'
44
- val discountRate = 0.2 // Inner variable shadows the outer variable
44
+ val discountRate = 0.2 // shadowing the outer variable discountRate
45
45
return price * (1 - discountRate) // 'price' here refers to the parameter, not the outer variable
46
46
}
47
47
@@ -50,7 +50,6 @@ class VariableShadowingUnitTest{
50
50
51
51
calculateTotalPrice(20 )
52
52
53
-
54
53
val numbers = listOf (1 , 2 , 3 , 4 , 5 )
55
54
56
55
// shadowing in loop
@@ -65,8 +64,8 @@ class VariableShadowingUnitTest{
65
64
// shadowing in extension
66
65
assertEquals(15 , numbers.sum())
67
66
68
- fun List<Int>.sum (): Int { // Shadowing occur in here
69
- var sum = 0 // shadowing built-in function sum()
67
+ fun List<Int>.sum (): Int { // shadowing built- in function sum()
68
+ var sum = 0
70
69
this .forEach { sum + = it * 2 }
71
70
return sum
72
71
}
@@ -76,9 +75,9 @@ class VariableShadowingUnitTest{
76
75
// shadowing in lambda
77
76
var sum = 0
78
77
79
- numbers.forEach { value ->
80
- val value = 0 // shadowing value
81
- sum + = value
78
+ numbers.forEach { number ->
79
+ val number = 0 // shadowing value
80
+ sum + = number
82
81
}
83
82
84
83
assertEquals(0 , sum)
0 commit comments