Introduction
Kotlin, a statically-typed programming language targeted at the JVM and Android, is designed to interoperate fully with Java while also offering various features and enhancements for safer and more concise code. This guide will take you through the basic syntax of Kotlin.
Variables
In Kotlin, you can define variables using two keywords: val for read-only variables and var for mutable ones.
val name: String = "John Doe" // Immutable variable
var age: Int = 25 // Mutable variableNote that Kotlin can infer types, so the type declarations are optional:
val name = "John Doe"
var age = 25Functions
Function declarations in Kotlin start with the keyword fun. Here is a simple example:
fun greet(name: String): String {
return "Hello, $name!"
}If you want to make your function even shorter, you can use the single-expression function syntax:
fun greet(name: String) = "Hello, $name!"Basic Control Flow
Kotlin supports the usual set of control flow constructs such as if, when, for, and while loops.
If Expression
The if construct is an expression and can return a value:
val max = if (a > b) a else bWhen Expression
The when construct in Kotlin can be used as a replacement for switch-case. Here's an example:
val x = 3
val result = when (x) {
1 -> "One"
2, 3 -> "Two or Three"
else -> "Unknown"
}Loops
Kotlin provides various ways to create loops. Here are some common examples:
For Loop
You can iterate over ranges and collections effortlessly using the for loop:
for (i in 1..5) {
println(i)
}While Loop
The while loop functions similarly to other languages:
var x = 5
while (x > 0) {
println(x)
x--
}Conclusion
This quick tour provides just a glimpse of Kotlin's concise and expressive syntax. As you explore further, you'll find more exciting features such as extension functions, null safety, and coroutines that make Kotlin a powerful tool in your programming arsenal.