Kotlin Cheat Sheet
Complete reference guide for Kotlin with interactive examples and live playground links
Basic Syntax
Hello World
Basic Kotlin program structure and functions
Kotlin
// Basic program
fun main() {
println("Hello, World!")
}
// Function with parameters
fun greet(name: String) {
println("Hello, $name!")
}
Variables and Data Types
Variable declaration and basic data types
Kotlin
// Variable declaration
var mutableVar = "Can be changed"
val immutableVal = "Cannot be changed"
// Type inference
val name = "Kotlin" // String
val age = 25 // Int
val height = 1.75 // Double
val isActive = true // Boolean
// Explicit type declaration
val score: Int = 100
val price: Double = 99.99
val letter: Char = 'A'
// Nullable types
var nullableName: String? = null
var nullableAge: Int? = null
// Type conversion
val intValue = 42
val longValue = intValue.toLong()
val stringValue = intValue.toString()
String Operations
String operations and templates
Kotlin
val text = "Hello Kotlin"
// String methods
println(text.length) // 12
println(text.uppercase()) // HELLO KOTLIN
println(text.lowercase()) // hello kotlin
println(text.replace("Kotlin", "World")) // Hello World
println(text.substring(0, 5)) // Hello
// String templates
val name = "Alice"
val age = 25
println("Name: $name, Age: $age")
println("Next year age: ${age + 1}")
// Multiline strings
val multiline = """
Line 1
Line 2
Line 3
""".trimIndent()
Collections
Lists and Arrays
Working with lists and arrays
Kotlin
// Lists
val numbers = listOf(1, 2, 3, 4, 5)
val mutableNumbers = mutableListOf(1, 2, 3)
// List operations
numbers.add(6) // Add element
numbers.remove(3) // Remove element
numbers[0] = 10 // Update element
println(numbers.size) // Get size
println(numbers.first()) // First element
println(numbers.last()) // Last element
// Arrays
val array = arrayOf(1, 2, 3, 4, 5)
val typedArray = IntArray(5) { it * 2 }
// List comprehension
val squares = List(5) { it * it }
val evenNumbers = (1..10).filter { it % 2 == 0 }
Maps and Sets
Working with maps and sets
Kotlin
// Maps
val map = mapOf(
"name" to "John",
"age" to 30,
"city" to "New York"
)
val mutableMap = mutableMapOf<String, Any>()
// Map operations
mutableMap["job"] = "Developer" // Add/update
mutableMap.remove("age") // Remove
println(map["name"]) // Access
println(map.containsKey("age")) // Check key
// Sets
val set = setOf(1, 2, 3, 3, 4) // Duplicates removed
val mutableSet = mutableSetOf<Int>()
// Set operations
mutableSet.add(5) // Add
mutableSet.remove(3) // Remove
println(set.contains(2)) // Check existence
// Set operations
val set1 = setOf(1, 2, 3)
val set2 = setOf(3, 4, 5)
println(set1.union(set2)) // [1, 2, 3, 4, 5]
println(set1.intersect(set2)) // [3]
println(set1.subtract(set2)) // [1, 2]
Functions
Function Types
Different types of functions in Kotlin
Kotlin
// Basic function
fun add(a: Int, b: Int): Int {
return a + b
}
// Single-expression function
fun multiply(a: Int, b: Int) = a * b
// Function with default parameters
fun greet(name: String = "Guest") = "Hello, $name!"
// Function with vararg
fun sum(vararg numbers: Int) = numbers.sum()
// Extension function
fun String.addExclamation() = "$this!"
// Higher-order function
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
// Usage
val result = calculate(5, 3) { a, b -> a + b }
Lambda Expressions
Lambda expressions and their usage
Kotlin
// Lambda syntax
val sum = { x: Int, y: Int -> x + y }
val square = { x: Int -> x * x }
// Lambda with receiver
val buildString = StringBuilder().apply {
append("Hello")
append(" ")
append("World")
}
// Collection operations with lambdas
val numbers = listOf(1, 2, 3, 4, 5)
// Map
val doubled = numbers.map { it * 2 }
// Filter
val evenNumbers = numbers.filter { it % 2 == 0 }
// Reduce
val sum = numbers.reduce { acc, num -> acc + num }
// ForEach
numbers.forEach { println(it) }
Classes and Objects
Class Definition
Class definition and data classes
Kotlin
// Basic class
class Person(
val name: String,
var age: Int
) {
// Secondary constructor
constructor() : this("Unknown", 0)
// Properties
var email: String = ""
private set
// Methods
fun greet() = "Hello, I'm $name"
// Companion object
companion object {
fun create(name: String) = Person(name, 0)
}
}
// Data class
data class User(
val id: Int,
val name: String,
val email: String
)
// Usage
val person = Person("John", 30)
val user = User(1, "Alice", "alice@example.com")
Inheritance and Interfaces
Inheritance, interfaces, and sealed classes
Kotlin
// Interface
interface Drawable {
fun draw()
fun getArea(): Double
}
// Abstract class
abstract class Shape {
abstract fun getArea(): Double
fun getPerimeter(): Double = 0.0
}
// Class implementing interface
class Circle(val radius: Double) : Shape(), Drawable {
override fun draw() {
println("Drawing circle")
}
override fun getArea(): Double {
return Math.PI * radius * radius
}
}
// Sealed class
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
}
// Usage
val circle = Circle(5.0)
println(circle.getArea())
Coroutines
Basic Coroutines
Basic coroutine usage and patterns
Kotlin
import kotlinx.coroutines.*
// Launch coroutine
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
// Async coroutine
suspend fun fetchData(): String {
delay(1000L)
return "Data"
}
// Coroutine scope
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
val result = async { fetchData() }.await()
println(result)
}
// Coroutine context
withContext(Dispatchers.IO) {
// IO operations
}
withContext(Dispatchers.Default) {
// CPU-intensive operations
}
Coroutine Patterns
Coroutine patterns and best practices
Kotlin
// Exception handling
try {
coroutineScope {
val result = async { fetchData() }.await()
}
} catch (e: Exception) {
println("Error: ${e.message}")
}
// Structured concurrency
val job = launch {
val result1 = async { fetchData1() }
val result2 = async { fetchData2() }
println("${result1.await()} ${result2.await()}")
}
// Coroutine cancellation
val job = launch {
try {
repeat(1000) { i ->
println("Job: I'm sleeping $i ...")
delay(500L)
}
} catch (e: CancellationException) {
println("Job cancelled")
}
}
delay(1300L)
job.cancel()
Kotlin - Interactive Developer Reference
Hover over code blocks to copy or run in live playground