Sobes.tech
Intern

How is a variable declared in Kotlin programming language for Android?

sobes.tech AI

Answer from AI

In Kotlin, variables are declared using the keywords val (for immutable variables) and var (for mutable variables). The variable type can be explicitly specified or inferred by the compiler.

val name: String = "Kotlin" // Immutable variable with explicit String type
var count: Int = 10       // Mutable variable with explicit Int type

val language = "Kotlin" // Immutable variable, type inferred as String
var version = 1.6       // Mutable variable, type inferred as Double

Variables are declared within a class body, functions, or at the top level of a file.

In Android development, variables are often used to store references to View elements, data from SharedPreferences, network request results, etc.

Example inside a class:

class MyActivity : AppCompatActivity() {

    private lateinit var textView: TextView // lateinit for deferred initialization of a non-null variable

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

        textView = findViewById(R.id.myTextView) // Assigning a value
        textView.text = "Hello, Android!"
    }
}
How is a variable declared in Kotlin programming… - sobes.tech