Home > Enterprise >  Kotlin Global Variable Showing As Zero "0"
Kotlin Global Variable Showing As Zero "0"

Time:12-08

I am a complete beginner and have started to learn Kotlin via YouTube tutorials and Google searching for specifics. When I was following a tutorial, he created three variables inside the MainActivity class as the following

class MainActivity : AppCompatActivity() {

var firstName= "David"
var secondName= "Tal"
var age = 20

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

Next, he uses the created variables in a private function like this:

private fun nameRating(){
   if(firstName == secondName){
      Toast.makeText(applicationContext,"10/10", Toast.LENGTH_LONG).show()
   }else{
      Toast.makeText(applicationContext,"5/10", Toast.LENGTH_LONG).show()
   }}

I followed the example and recreated it in Android Studio, but the if condition triggered, and I thought it was weird. After debugging it turned out that both firstName and secondName are "0". I thought the variables were supposed to be global, and it is confusing why it is not working because the age variable is correct.

If I am completely wrong on how this should work, any explanation/clarification on the matter would be appreciated.

CodePudding user response:

Don't worry, Kotlin is not doing anything weird or magical behind your back in this case.

The var keyword in Kotlin means that you are declaring a variable, but the scope of that variable is not "global". The scope is the code block in which the variable is declared. In your case, you declared 3 variables in a class scope, so these are class variables and they can be accessed from anywhere inside the class MainActivity. Since they are also public (by default in Kotlin declarations are public, unless you specify a different access modifier, such as private, protected etc.), these 3 variables can also be accessed from outside the class (or from a subclass), as long as the calling code has a reference to an instance of this class. This works the same in Java, if something is public same access rules apply.

Since these are variables (their value can change) it also means that any code that has access to them, can also change their values. So the "weird" behavior that you are experiencing is likely due to some other part of code setting firstName and secondName to "0" before your nameRating() function is called, and that is why firstName and secondName are equal and the if condition evaluates to true.

In Android Studio, you can right-click on one of your variables and select "Find Usages". Search results will show up, and there you will see parts in code where other code might be changing the values of your variables. Hopefully that will shed some light on this behavior that you are seeing.

  • Related