Kotlin-Cheatsheet

👋 Hello Kotlin

fun main() {
    println("Hello, Kotlin!")
}

💡 Tip: Use println() for console output. Kotlin is fully interoperable with Java.

📦 Variables & Data Types

fun main() {
    val name: String = "Maxon"   // immutable
    var age: Int = 25            // mutable
    val pi = 3.14159             // type inferred
    val isActive: Boolean = true
    val letter: Char = 'A'

    println("$name is $age years old.")
}

💡 Tip: Prefer val for immutability; Kotlin infers types automatically.

🔀 Control Flow

fun main() {
    // if-else
    val x = 10
    if(x > 5) println("x > 5") else println("x <= 5")

    // for loop
    for(i in 1..5) println(i)

    // while loop
    var i = 1
    while(i <= 5) {
        println(i)
        i++
    }

    // when expression
    val y = 2
    when(y) {
        1 -> println("One")
        2 -> println("Two")
        else -> println("Other")
    }
}

💡 Tip: when replaces switch and can return values.

🛠 Functions

fun add(a: Int, b: Int): Int = a + b

fun main() {
    println(add(5, 3))

    // Default arguments
    fun greet(name: String = "Guest") = println("Hello, $name")
    greet()
    greet("Maxon")

    // Vararg
    fun sumAll(vararg nums: Int) = nums.sum()
    println(sumAll(1,2,3,4))
}

💡 Tip: Kotlin supports default arguments, named parameters, and varargs for flexibility.

🏛 Classes & Objects

class Car(var brand: String, var speed: Int) {
    fun drive() = println("$brand drives at $speed km/h")
}

fun main() {
    val car = Car("Tesla", 120)
    car.drive()
}

💡 Tip: Kotlin generates getters/setters automatically. Use concise primary constructors for clean code.

🧬 Inheritance

open class Animal {
    open fun sound() = println("Some sound")
}

class Dog : Animal() {
    override fun sound() = println("Woof!")
}

fun main() {
    val dog = Dog()
    dog.sound()
}

💡 Tip: Use open for classes or functions that can be overridden.

💾 Data Classes

data class User(val name: String, val age: Int)

fun main() {
    val user1 = User("Maxon", 25)
    val user2 = user1.copy(age = 26)
    println(user1)
    println(user2)
}

💡 Tip: Data classes automatically provide equals, hashCode, toString, and copy.

🔒 Sealed Classes

sealed class Result
class Success(val data: String) : Result()
class Error(val message: String) : Result()

fun handle(result: Result) {
    when(result) {
        is Success -> println(result.data)
        is Error -> println(result.message)
    }
}

💡 Tip: Sealed classes allow exhaustive when checks for type safety.

📚 Collections

fun main() {
    val nums = listOf(1,2,3,4,5)       // immutable
    val mutableNums = mutableListOf(1,2,3)
    mutableNums.add(4)

    // Map
    val map = mapOf("a" to 1, "b" to 2)

    // Iteration
    nums.forEach { println(it) }

    // Functional
    val even = nums.filter { it % 2 == 0 }.map { it * 2 }
    println(even)
}

💡 Tip: Use functional operations like map, filter, reduce for concise code.

❌ Null Safety

fun main() {
    var name: String? = null
    println(name?.length)       // safe call
    println(name ?: "Unknown")  // Elvis operator
    name?.let { println(it) }   // execute block if not null
}

💡 Tip: Nullable types reduce NullPointerExceptions. Use ?., ?:, and let.

⚡ Lambdas & Higher-Order Functions

fun main() {
    val square: (Int) -> Int = { x -> x * x }
    println(square(5))

    fun operate(a: Int, b: Int, op: (Int, Int) -> Int) = op(a, b)
    println(operate(5,3) { x, y -> x + y })
}

💡 Tip: Higher-order functions accept functions as parameters or return functions for flexibility.

🧩 Extension Functions

fun String.firstChar(): Char = this[0]

fun main() {
    println("Maxon".firstChar())  // Output: M
}

💡 Tip: Use extension functions to add functionality to existing classes without inheritance.

🎯 Generics

fun  List.second(): T? = if(size >= 2) this[1] else null

fun main() {
    val list = listOf(1,2,3)
    println(list.second())
}

💡 Tip: Generics increase code reusability and type safety.

🪝 Delegates

import kotlin.properties.Delegates

class User {
    var name: String by Delegates.observable("") { prop, old, new ->
        println("$old -> $new")
    }
}

fun main() {
    val user = User()
    user.name = "Maxon"
    user.name = "Alex"
}

💡 Tip: Delegates help implement observable properties, lazy initialization, or storing values efficiently.

⏱ Coroutines

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000)
        println("Hello from coroutine!")
    }
    println("Hello from main!")
}

💡 Tip: Coroutines simplify asynchronous programming without blocking threads.

📦 Standard Library Utilities

fun main() {
    println("max".uppercase())
    println("Kotlin".contains("lin"))
    val nums = listOf(1,2,3)
    println(nums.sum())
    println(nums.joinToString(", "))
}

💡 Tip: Kotlin standard library is rich with extensions for strings, collections, numbers, and more.

Post a Comment