In Kotlin, variables are used to store values that can be accessed and modified throughout the course of a program. Here are the basic concepts of variables in Kotlin:
Declaration: In Kotlin, you can declare variables using the val
or var
keywords. The val
keyword is used to declare an immutable variable (i.e., a variable whose value cannot be changed once it’s assigned), while the var
keyword is used to declare a mutable variable (i.e., a variable whose value can be changed).
val name: String = "Alice" // Immutable variable
var age: Int = 30 // Mutable variable
Type inference: In Kotlin, you can omit the type declaration for a variable if the variable is initialized with a value. The Kotlin compiler can infer the type of the variable based on the type of the value.
val greeting = "Hello" // Type inference - greeting is a String
var count = 0 // Type inference - count is an Int
Null safety: In Kotlin, all variables are non-nullable by default, which means that they cannot hold a null value. To declare a variable that can hold a null value, you can use the ?
operator.
val nullableName: String? = null // Nullable variable
Scope: In Kotlin, the scope of a variable is determined by the block of code in which it is declared. A variable declared inside a block of code is only accessible within that block and any nested blocks. Variables declared outside a block of code are accessible throughout the entire file.
fun main() {
val x = 5 // x is accessible within main() function
if (x > 3) {
val y = 10 // y is accessible only within this block
println(x + y)
}
println(x)
}
Naming conventions: In Kotlin, variables should follow the same naming conventions as in Java. Variable names should start with a lowercase letter, and if the name consists of multiple words, each word should start with an uppercase letter (camel case).
Variable naming rules in Kotlin or Java
val firstName: String = "John"
var itemCount: Int = 5
By understanding these basic concepts of variables in Kotlin, you can effectively use them to store and manipulate data in your programs.