1. Basic Syntax & Variables Hello World: fun main() { println("Hello, World!") } Variables: Mutable: var name: String = "Alice" Immutable: val age: Int = 30 Type Inference: val pi = 3.14 (automatically infers Double) Nullable Types: var city: String? = null Data Types: Int , Double , Float , Long , Short , Byte , Boolean , Char , String . Comments: Single-line: // This is a comment Multi-line: /* This is also a comment */ 2. Functions Basic Function: fun greet(name: String): String { return "Hello, $name!" } Inferred Return Type: fun sum(a: Int, b: Int) = a + b Unit (Void) Return: fun printMessage(msg: String): Unit { // Unit can be omitted println(msg) } Default Arguments: fun log(msg: String, level: String = "INFO") { println("[$level] $msg") } log("User logged in") // INFO log("Error occurred", "ERROR") Named Arguments: fun createPoint(x: Int, y: Int) = "($x, $y)" createPoint(y = 10, x = 5) Varargs (Variable Number of Arguments): fun printAll(vararg messages: String) { for (m in messages) println(m) } printAll("a", "b", "c") 3. Control Flow If-Else Expression: val max = if (a > b) a else b Can be used as an expression, returning a value. When Expression (Switch): val result = when (x) { 1 -> "One" 2, 3 -> "Two or Three" in 4..10 -> "Between 4 and 10" is Int -> "Is an Integer" else -> "Other" } For Loop: Range: for (i in 1..5) println(i) DownTo: for (i in 5 downTo 1) println(i) Step: for (i in 1..10 step 2) println(i) Collections: for (item in list) println(item) With Index: for ((index, item) in list.withIndex()) println("$index: $item") While Loop: var i = 0 while (i Do-While Loop: var j = 0 do { println(j++) } while (j Break & Continue: break : Terminates the innermost loop. continue : Proceeds to the next step of the innermost loop. Labels for non-local control: loop@ for (i in 1..10) { for (j in 1..10) { if (i == 5 && j == 5) break@loop } } 4. Classes & Objects Basic Class: class Person { var name: String = "Unknown" var age: Int = 0 } val person = Person() person.name = "Alice" Primary Constructor: class User(val id: Int, var name: String) val user = User(1, "Bob") println(user.name) Secondary Constructors: class Animal { var species: String constructor(species: String) { this.species = species } } Data Classes: data class Product(val id: Int, val name: String, val price: Double) val p1 = Product(1, "Laptop", 1200.0) val p2 = p1.copy(price = 1100.0) // Copy with modifications println(p1.toString()) // Auto-generated toString, equals, hashCode, copy Enums: enum class Direction { NORTH, SOUTH, EAST, WEST } val dir = Direction.NORTH Object Declarations (Singleton): object Logger { fun log(msg: String) = println("LOG: $msg") } Logger.log("App started") Companion Objects: (Static-like members for a class) class MyClass { companion object { const val PI = 3.14159 // Compile-time constant fun create(): MyClass = MyClass() } } val instance = MyClass.create() 5. Inheritance & Interfaces Inheritance: Classes are final by default. Use open to allow inheritance. Methods are final by default. Use open to allow overriding, override to override. open class Shape { open fun draw() { /* ... */ } } class Circle : Shape() { override fun draw() { /* ... */ } } Abstract Classes: abstract class Vehicle { abstract fun start() fun stop() { /* ... */ } } class Car : Vehicle() { override fun start() { /* ... */ } } Interfaces: Can contain abstract methods and concrete method implementations. Properties can be declared abstract or provide accessors. interface Clickable { fun click() fun showOff() = println("I'm clickable!") } class Button : Clickable { override fun click() { /* ... */ } } 6. Null Safety Nullable Types: Declared with ? : var name: String? = null Non-nullable by default: var id: Int = 1 Safe Call Operator ( ?. ): val length = name?.length // Returns null if name is null, otherwise length Elvis Operator ( ?: ): val len = name?.length ?: 0 // Returns 0 if name or name.length is null Non-Null Assertion Operator ( !! ): val len = name!!.length // Throws NullPointerException if name is null Use with caution, only when you are absolutely sure it's not null. Safe Cast ( as? ): val obj: Any = "Hello" val str: String? = obj as? String // str is "Hello" val num: Int? = obj as? Int // num is null 7. Collections Lists: Immutable: val list = listOf("apple", "banana") Mutable: val mutableList = mutableListOf(1, 2, 3) Access: list[0] , list.get(0) Add/Remove: mutableList.add(4) , mutableList.removeAt(0) Sets: Immutable: val set = setOf(1, 2, 3, 3) (stores unique elements) Mutable: val mutableSet = mutableSetOf("a", "b") Maps: Immutable: val map = mapOf("key1" to "value1", "key2" to "value2") Mutable: val mutableMap = mutableMapOf(1 to "one", 2 to "two") Access: map["key1"] , map.get("key1") Add/Update: mutableMap[3] = "three" Common Operations: .size , .isEmpty() , .contains() Iteration: for (item in list) or list.forEach { println(it) } 8. Extension Functions & Properties Extension Function: Add new functionality to an existing class without modifying its source. fun String.addExclamation(): String { return this + "!" } val greeting = "Hello".addExclamation() // "Hello!" Extension Property: val String.firstChar: Char get() = this[0] val char = "Kotlin".firstChar // 'K' 9. Higher-Order Functions & Lambdas Lambda Expression: A function literal (a function not declared, but passed immediately as an expression). val sum = { a: Int, b: Int -> a + b } val result = sum(5, 3) // 8 Trailing Lambda Syntax: If a lambda is the last argument, it can be moved outside the parentheses. val list = listOf(1, 2, 3) list.filter { it > 1 } // { it > 1 } is the lambda Higher-Order Function: A function that takes functions as parameters or returns a function. fun operate(a: Int, b: Int, op: (Int, Int) -> Int): Int { return op(a, b) } val res = operate(10, 5) { x, y -> x * y } // 50 Common Higher-Order Functions: map : Transforms elements. list.map { it * 2 } filter : Selects elements. list.filter { it % 2 == 0 } forEach : Iterates. list.forEach { println(it) } reduce : Combines elements. list.reduce { acc, i -> acc + i } fold : Combines with initial value. list.fold(0) { acc, i -> acc + i } 10. Generics Generic Class: class Box (val item: T) val intBox = Box(123) val stringBox = Box("Hello") Generic Function: fun identity(value: T): T { return value } val num = identity(42) Type Constraints: fun > maxOf(a: T, b: T): T { return if (a > b) a else b } Variance ( in , out ): out (Covariant): Producer. Allows assignment to a supertype. interface Producer in (Contravariant): Consumer. Allows assignment to a subtype. interface Consumer 11. Coroutines (Basics) Lightweight Threads: For asynchronous programming. suspend Modifier: Marks a function that can be paused and resumed. suspend fun fetchData(): String { delay(1000) // Non-blocking delay return "Data" } launch Coroutine Builder: Starts a new coroutine in the background. import kotlinx.coroutines.* fun main() = runBlocking { // Blocks the main thread until all coroutines complete launch { println("Coroutine started") delay(500) println("Coroutine finished") } println("Main continues") } async Coroutine Builder: Starts a coroutine and returns a Deferred result. val deferred = async { fetchData() } val data = deferred.await() // Waits for the result Dispatchers: Define the thread pool where coroutines run. Dispatchers.Main (for UI updates) Dispatchers.IO (for network/disk operations) Dispatchers.Default (for CPU-intensive tasks) launch(Dispatchers.IO) { /* ... */ } 12. Exception Handling try-catch-finally : try { val result = 10 / 0 } catch (e: ArithmeticException) { println("Error: ${e.message}") } finally { println("Execution complete") } try as an Expression: val num: Int? = try { "123".toInt() } catch (e: NumberFormatException) { null } 13. Miscellaneous Features String Templates: val name = "Alice" println("Hello, $name! Today is ${java.time.LocalDate.now()}") Ranges: val r1 = 1..5 // Inclusive: 1, 2, 3, 4, 5 val r2 = 1 until 5 // Exclusive: 1, 2, 3, 4 val r3 = 'a'..'z' Type Checks & Smart Casts: fun printLength(obj: Any) { if (obj is String) { println(obj.length) // obj is automatically cast to String } } Destructuring Declarations: data class Point(val x: Int, val y: Int) val (x, y) = Point(10, 20) println("x=$x, y=$y") Also works with maps: for ((key, value) in map) { ... } Sealed Classes: Restrict inheritance to a defined set of subclasses. sealed class Result { data class Success(val data: String) : Result() data class Error(val message: String) : Result() } fun handleResult(res: Result) = when (res) { is Result.Success -> println(res.data) is Result.Error -> println(res.message) } Type Aliases: Provide an alternative name for an existing type. typealias Name = String typealias Predicate = (T) -> Boolean val myName: Name = "Bob"