Variables in Kotlin

In Kotlin, variables are explicitly declared and used by the compiler to check type-correctness of function calls.

fun main() {
    // 'var' declares a mutable variable
    var a = "initial"
    println(a)

    // You can declare multiple variables at once
    var b = 1
    var c = 2
    println("$b $c")

    // Kotlin will infer the type of initialized variables
    var d = true
    println(d)

    // Variables declared without initialization must specify the type
    var e: Int
    e = 0 // Initialization is required before use
    println(e)

    // 'val' declares an immutable variable (similar to 'final' in Java)
    val f = "apple"
    println(f)
}

To run the program, save it as variables.kt and use the Kotlin compiler:

$ kotlinc variables.kt -include-runtime -d variables.jar
$ java -jar variables.jar
initial
1 2
true
0
apple

In this Kotlin example:

  1. We use var to declare mutable variables, which can be reassigned.
  2. Type inference is used when initializing variables, so we don’t need to specify types explicitly in most cases.
  3. When declaring a variable without initialization, we must specify its type.
  4. Kotlin uses val for read-only variables, which is similar to using final in Java or const in some other languages.
  5. String templates ("$b $c") are used for string interpolation.
  6. The println() function is used for console output, similar to System.out.println() in Java.

Kotlin doesn’t have a direct equivalent to Go’s := syntax, as variable declaration and initialization are already concise in Kotlin. The type inference system in Kotlin automatically determines the type of a variable when it’s initialized, making the code clean and readable.