Scala: accessing shadowed parameter/variable -


i have following code, , 2 situations inside the

  1. if in method hidevariablefromouterblock declaring variable k shadows 1 defined in outer block.
  2. inside second method hideparametername declaring variable k 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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -