-1

a very simple question regarding Kotlin. What if a global variable (in function context) has the same name as a local variable declared within if statement. As you can see there are two msg variables, how to call outsider msg within if statement.

fun main() {

    var point = 100

    var msg = "Kotlin"

    if(point >= 50) {

        var msg = "Java"

        // print msg Java
        println(msg)

        // How to print msg Kotlin instead of Java
        println(msg)

    }
}
abidkhan303
  • 1,761
  • 3
  • 18
  • 31
  • 1
    That's not a global variable, that's just another local variable with a wider scope. The second `msg` is said to "shadow" the first, meaning the first cannot be accessed. – Nicolas Aug 01 '20 at 21:03

1 Answers1

0

This appears to not be possible:

Why kotlin allows to declare variable with the same name as parameter inside the method?

Just avoid shadowing, it's confusing anyway. Your IDE will probably tell you though.

Carlos
  • 5,991
  • 6
  • 43
  • 82