Kotlin
Updated: September 10, 2025Categories: Languages, Mobile
Printed from:
Kotlin Cheatsheet
Language Overview
Kotlin is a modern, statically-typed programming language developed by JetBrains. Key features include:
- 100% interoperability with Java
- Null safety
- Concise and expressive syntax
- First-class support for functional programming
- Runs on the Java Virtual Machine (JVM)
- Supports multiplatform development
Basic Syntax
Hello World
Kotlin
1234fun main() {
println("Hello, Kotlin!")
}
Comments
Kotlin
123456// Single-line comment
/*
Multi-line
comment
*/
/**
* Documentation comment
* Used for generating API documentation
*/
Data Types
Primitive Types
Kotlin
12345678910111213141516171819// Integers
val byte: Byte = 127 // 8-bit signed integer
val short: Short = 32767 // 16-bit signed integer
val int: Int = 2_147_483_647 // 32-bit signed integer
val long: Long = 9_223_372_036_854_775_807L // 64-bit signed integer
// Floating Point
val float: Float = 3.14f // 32-bit floating point
val double: Double = 3.14159 // 64-bit floating point
// Boolean
val bool: Boolean = true
// Character
val char: Char = 'A'
// String
val str: String = "Kotlin is awesome!"
Nullable Types
Kotlin
1234567891011// Nullable vs Non-Nullable Types
var nonNullableInt: Int = 42 // Cannot be null
var nullableInt: Int? = null // Can be null
var nullSafetyExample: String? = null
// Safe call operator
val length = nullableInt?.length // Returns null if nullableInt is null
// Elvis operator (provide default value)
val safeLength = nullableInt?.length ?: 0
Collection Types
Kotlin
12345678910111213141516// Immutable Lists
val immutableList: List<String> = listOf("Apple", "Banana", "Cherry")
// Mutable Lists
val mutableList: MutableList<String> = mutableListOf("Apple", "Banana")
mutableList.add("Cherry")
// Sets
val immutableSet: Set<Int> = setOf(1, 2, 3)
val mutableSet: MutableSet<Int> = mutableSetOf(1, 2, 3)
// Maps
val immutableMap: Map<String, Int> = mapOf("one" to 1, "two" to 2)
val mutableMap: MutableMap<String, Int> = mutableMapOf("one" to 1)
mutableMap["two"] = 2
Variables and Constants
Kotlin
12345678910111213141516171819// Immutable variable (read-only, like final in Java)
val pi: Double = 3.14159
// Mutable variable
var counter: Int = 0
// Type inference
val name = "Kotlin" // Type is inferred as String
var age = 30 // Type is inferred as Int
// Late initialization
lateinit var lateInitVar: String
// Lazy initialization
val expensiveValue: String by lazy {
// Computed only on first access
"Expensive Computation"
}
Operators
Arithmetic Operators
Kotlin
123456val sum = 5 + 3 // Addition
val diff = 5 - 3 // Subtraction
val prod = 5 * 3 // Multiplication
val div = 6 / 3 // Division
val mod = 5 % 3 // Modulus
Comparison Operators
Kotlin
123456789val a = 5
val b = 3
println(a == b) // Equality check
println(a != b) // Inequality check
println(a > b) // Greater than
println(a < b) // Less than
println(a >= b) // Greater than or equal
println(a <= b) // Less than or equal
Logical Operators
Kotlin
1234567val x = true
val y = false
println(x && y) // Logical AND
println(x || y) // Logical OR
println(!x) // Logical NOT
Control Structures
Conditional Statements
Kotlin
1234567891011121314151617// If-Else
if (x > y) {
println("x is greater")
} else if (x < y) {
println("y is greater")
} else {
println("x and y are equal")
}
// When Expression (advanced switch)
when (x) {
1 -> println("x is 1")
2, 3 -> println("x is 2 or 3")
in 4..10 -> println("x is between 4 and 10")
else -> println("x is something else")
}
Loops
Kotlin
12345678910111213141516171819202122232425262728293031// For Loop
for (i in 1..5) {
println(i)
}
// Iterating over collections
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
// While Loop
var counter = 0
while (counter < 5) {
println(counter)
counter++
}
// Do-While Loop
do {
println(counter)
counter--
} while (counter > 0)
// Break and Continue
for (i in 1..10) {
if (i == 5) continue // Skip 5
if (i == 8) break // Exit loop
println(i)
}
Functions
Basic Functions
Kotlin
12345678910111213141516171819// Function with return type
fun add(a: Int, b: Int): Int {
return a + b
}
// Single-expression function
fun multiply(a: Int, b: Int) = a * b
// Function with default arguments
fun greet(name: String = "World") {
println("Hello, $name!")
}
// Named Arguments
fun createUser(name: String, age: Int = 0, email: String = "") {
// User creation logic
}
createUser(name = "John", email = "john@example.com")
Lambda Functions
Kotlin
123456789// Lambda expression
val sum = { a: Int, b: Int -> a + b }
println(sum(3, 5)) // Prints 8
// Higher-order functions
val numbers = listOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
val filtered = numbers.filter { it % 2 == 0 }
Object-Oriented Programming
Classes and Objects
Kotlin
1234567891011121314151617181920212223// Basic class
class Person(val name: String, var age: Int) {
fun introduce() {
println("Hi, I'm $name and I'm $age years old")
}
}
// Data Class (automatic equals, hashCode, toString)
data class User(val id: Int, val username: String)
// Inheritance
open class Animal {
open fun makeSound() {
println("Some sound")
}
}
class Dog : Animal() {
override fun makeSound() {
println("Woof!")
}
}
Extension Functions
Kotlin
1234567// Add methods to existing classes
fun String.removeWhitespace(): String {
return this.replace("\\s".toRegex(), "")
}
val cleanString = "Hello World".removeWhitespace()
Error Handling
Kotlin
123456789101112131415// Try-Catch
try {
// Code that might throw an exception
val result = 10 / 0
} catch (e: ArithmeticException) {
println("Cannot divide by zero")
} finally {
println("Cleanup code")
}
// Throwing Exceptions
fun validateAge(age: Int) {
require(age >= 0) { "Age cannot be negative" }
}
File I/O
Kotlin
12345678910111213import java.io.File
// Reading a file
val content = File("example.txt").readText()
// Writing to a file
File("output.txt").writeText("Hello, Kotlin!")
// Using Buffered Reader
File("example.txt").bufferedReader().use { reader ->
val lines = reader.readLines()
}
Coroutines (Asynchronous Programming)
Kotlin
123456789101112131415161718import kotlinx.coroutines.*
// Basic Coroutine
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
// Async/Await
suspend fun fetchUserData(): String = withContext(Dispatchers.IO) {
// Simulate network call
delay(1000)
"User Data"
}
Common Libraries and Frameworks
Standard Library
kotlin.collections: Enhanced collection utilitieskotlin.text: String manipulationkotlin.io: File and I/O operations
Popular Frameworks
- Spring Boot: Enterprise Java application framework
- Ktor: Lightweight server-side framework
- Android Development: Primary language for Android
- Gradle Kotlin DSL: Build automation
Best Practices
Code Style
- Use meaningful variable and function names
- Prefer immutability (
valovervar) - Utilize type inference
- Leverage null safety features
Performance Tips
- Use
inlinefunctions for small lambdas - Prefer
sequencefor large collection operations - Minimize object creation in performance-critical code
Testing
Kotlin
12345678// JUnit 5 Example
class CalculatorTest {
@Test
fun `addition works correctly`() {
assertEquals(5, 2 + 3)
}
}
Resources for Further Learning
- Official Kotlin Documentation: https://kotlinlang.org/docs/
- Kotlin Koans: Online interactive tutorials
- Coursera and Udacity Kotlin Courses
- JetBrains Kotlin YouTube Channel
- Books: "Kotlin in Action", "Head First Kotlin"
Multiplatform Development
Kotlin supports:
- JVM
- Android
- JavaScript
- Native (iOS, macOS, Windows, Linux)
Conclusion
Kotlin offers a modern, concise, and safe programming experience with seamless Java interoperability and powerful language features.
Continue Learning
Discover more cheatsheets to boost your productivity