Scala: accessing shadowed parameter/variable -
i have following code, , 2 situations inside the
if
in methodhidevariablefromouterblock
declaring variablek
shadows 1 defined in outer block.- inside second method
hideparametername
declaring variablek
shadows parameter same name.
object test extends app { def hidevariablefromouterblock() = { var k = 2457 if (k % 2 != 0) { var k = 47 println(k) // prints 47 //println(outer k) } println(k) // - prints 2457 expected } def hideparametername(k: int) = { var k = 47 println(k) // prints 47 //println(parameter k) } hidevariablefromouterblock() hideparametername(2457) }
is there way in blocks have shadowed variable or parameter k
access shadowed value (the variable outer block)?
i aware not practice, , never that. asking question educational purposes.
i did bit of research , failed find clear explanation. find/see shadowing occurs, found no clear explanation variable outer block can't accessed anymore.
i newbie in scala.
this answer talks why shadowing allowed in first place.
as way access shadowed value, simplest thing far know rename inner variable , problem goes away. suppose, sake of exercise, if don't want rename anything, assign outer variable new 1 different name.
var k = 2457 val outer_k = k if (k % 2 != 0) { var k = 47 println(k) // prints 47 println(outer_k) }
Comments
Post a Comment