kotlin access variable from another class
To access a variable from another class in Kotlin, you can follow these steps:
- Declare the variable in the source class: In the class where you want to access the variable, declare it using the
var
orval
keyword. For example:
class SourceClass {
var myVariable: String = "Hello"
}
- Create an instance of the source class: In the class where you want to access the variable, create an instance of the source class using the
new
keyword followed by the constructor. For example:
val source = SourceClass()
- Access the variable using the instance: Once you have created an instance of the source class, you can access the variable using the instance name followed by the dot operator. For example:
val value = source.myVariable
Now you have successfully accessed the variable myVariable
from the SourceClass
in another class.