In Java, we could create a global variable just by defining the variable at the beginning of class declaration and initializing it afterward. By just declaring it, we could use it as a global variable.
In this recipe, we will learn how to create and use a global variable in Kotin.
I'll be using IntelliJ for coding purposes. You can use any IDE where you can write and execute Kotlin code.
Now, let's look at how to create global variables in Kotlin. There are two ways to do it. Let's look at them one by one:
- One way to do it is by declaring it under the class declaration. We can use
var
declaration, like this:
fun main(args: Array<String>) { var student:Student?=null }
However, this approach will result in testing for nullability whenever you use it:
println(student?.age)
- To prevent this, you can declare and initialize it using
val
, but that will result in an immutable variable, which might not be the desired behavior. - Another way to declare...