Kotlin Cheat Sheet

Kotlin Cheat Sheet

1. Basics

val x = 10  // Immutable (read-only)
var y = 20  // Mutable (can be changed)

Data Types

val a: Int = 10
val b: Double = 10.5
val c: Boolean = true
val d: String = "Hello"
val e: List<Int> = listOf(1, 2, 3)
val f: MutableList<Int> = mutableListOf(4, 5, 6)

Functions

fun add(a: Int, b: Int): Int {
    return a + b
}

fun shortAdd(a: Int, b: Int) = a + b  // Single-expression function

String Interpolation

val name = "Kotlin"
println("Hello, $name!")

2. Control Flow

If-Else

val max = if (a > b) a else b

When (Switch Alternative)

when (x) {
    1 -> println("One")
    2 -> println("Two")
    else -> println("Other")
}

Loops

for (i in 1..5) println(i)  // Inclusive range
for (i in 1 until 5) println(i)  // Exclusive range
for (i in 5 downTo 1 step 2) println(i)  // Reverse and step

var count = 0
while (count < 5) {
    println(count++)
}

3. Classes and Objects

class Person(val name: String, var age: Int) {
    fun greet() = println("Hello, my name is $name and I am $age years old.")
}

val person = Person("Alice", 30)
person.greet()

Inheritance

open class Animal(val name: String) {
    open fun sound() = println("Some sound")
}

class Dog(name: String) : Animal(name) {
    override fun sound() = println("Bark")
}

4. Null Safety

var name: String? = "Kotlin"
name = null
println(name?.length)  // Safe call operator
println(name?.length ?: 0)  // Elvis operator

5. Collections

val numbers = listOf(1, 2, 3, 4, 5)
val mutableNumbers = mutableListOf(6, 7, 8)

val filtered = numbers.filter { it % 2 == 0 }
val mapped = numbers.map { it * 2 }

6. Extension Functions

fun String.hello() = "Hello, $this!"
println("Kotlin".hello())

7. Coroutines (Basics)

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000L)
        println("World!")
    }
    println("Hello")
}

8. Higher-Order Functions & Lambdas

fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

val result = operate(5, 3) { x, y -> x + y }
println(result)

9. Data Classes

data class User(val name: String, val age: Int)
val user = User("Alice", 25)
println(user.copy(age = 26))

10. Sealed Classes

sealed class Result
class Success(val data: String) : Result()
class Failure(val error: String) : Result()

fun handle(result: Result) {
    when (result) {
        is Success -> println("Success: ${result.data}")
        is Failure -> println("Error: ${result.error}")
    }
}

11. Companion Object

class MyClass {
    companion object {
        fun create() = MyClass()
    }
}
val obj = MyClass.create()

12. Generics

class Box<T>(val item: T) {
    fun getItem(): T = item
}

val intBox = Box(10)
println(intBox.getItem())

13. Delegation

interface Printer {
    fun printMessage()
}

class SimplePrinter : Printer {
    override fun printMessage() = println("Simple Print")
}

class AdvancedPrinter(p: Printer) : Printer by p

val printer = AdvancedPrinter(SimplePrinter())
printer.printMessage()

14. Operator Overloading

data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}

val p1 = Point(1, 2)
val p2 = Point(3, 4)
println(p1 + p2)

15. Type Aliases

typealias Name = String
val myName: Name = "Kotlin"

This Kotlin cheat sheet provides a concise reference for core concepts. Use it as a quick guide for your Kotlin development!

Comments

Popular posts from this blog

Tajdar-e-Haram Lyrics with English Translation - Atif Aslam - Coke Studio

Android Json Parsing and Image Loading Tutorial - Android Studio

Tragic Collision at Reagan National: Lessons from a Deadly Midair Disaster