Google's preferred language for Android development โ runs on the JVM alongside Java, but with modern conveniences like null safety built directly into the type system. Copy-paste examples plus live Run/Submit exercises.
fun main() {
println("Hello, world!")
}
val age = 25 // val = constant, can't change
var name = "Sam" // var = can change
val price: Double = 19.99
Kotlin's headline feature โ the type system tracks whether a value can be null, so a whole class of crashes gets caught at compile time.
var middleName: String? = null // the ? means "this can be null"
val length = middleName?.length ?: 0 // safe call + default fallback
println(length)
val age = 20
if (age >= 18) {
println("Adult")
} else if (age >= 13) {
println("Teen")
} else {
println("Child")
}
for (i in 0 until 5) {
println(i)
}
var n = 3
while (n > 0) {
println(n)
n--
}
Kotlin generates equals/hashCode/toString for you automatically for simple data holders.
data class Dog(val name: String, val age: Int) {
fun bark() {
println("$name says woof!")
}
}
// val d = Dog("Rex", 3); d.bark()
Full runnable programs, compiled and run in a real Kotlin sandbox โ same workspace as the other cheat sheets.
fun main() {
val nums = listOf(4, 8, 15, 16, 23, 42)
println(nums.sum())
}
fun main() {
val s = "kotlin"
println(s.reversed())
}
fun main() {
for (i in 1..15) {
when {
i % 15 == 0 -> println("FizzBuzz")
i % 3 == 0 -> println("Fizz")
i % 5 == 0 -> println("Buzz")
else -> println(i)
}
}
}
fun main() {
val text = "the cat sat on the mat the cat ran"
val counts = mutableMapOf<String, Int>()
for (word in text.split(" ")) {
counts[word] = (counts[word] ?: 0) + 1
}
for ((word, n) in counts) {
println("$word: $n")
}
}