Title here
Summary here
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:
var
to declare mutable variables, which can be reassigned.val
for read-only variables, which is similar to using final
in Java or const
in some other languages."$b $c"
) are used for string interpolation.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.