Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Kotlin Documentation

Concise, null-safe and the official language for Android development.

Kotlin is a modern, concise, statically typed language from JetBrains that runs on the JVM (and also compiles to JavaScript and native code). It is Google's preferred language for Android, fully interoperable with Java, and famous for null safety, data classes, extension functions and coroutines.

1. Introduction & Installation

  • Android: install Android Studio — Kotlin is built in.
  • JVM/backend: IntelliJ IDEA (Community) has Kotlin built in. Command line: install a JDK, then sdk install kotlin (SDKMAN) or brew install kotlin, or download the compiler from GitHub releases.
  • Try it online: play.kotlinlang.org.
kotlinc -version
kotlinc hello.kt -include-runtime -d hello.jar
java -jar hello.jar
fun main() {
    println("Hello, Codify!")
}

Output:

Hello, Codify!

⚠️ Common error: kotlinc: command not found — the compiler isn't on PATH. In IntelliJ/Android Studio you don't need it; just press Run.

2. Basic Syntax

  • fun main() is the entry point; semicolons are optional.
  • val = read-only variable, var = mutable. Types are inferred.
  • String templates: "Hi $name" and "${expr}".
fun main() {
    val name = "Asha"
    var score = 90
    score += 5
    println("$name scored $score")
    println("Next level at ${score + 10} points")
    println("Length of name: ${name.length}")
}

Output:

Asha scored 95
Next level at 105 points
Length of name: 4

⚠️ Common error: Val cannot be reassigned — use var if the value must change (but prefer val wherever possible).

3. Variables & Data Types

Type Example
Int, Long val n = 42, val big = 9_000_000_000L
Double, Float val pi = 3.14, val f = 2.5f
Boolean, Char true, 'K'
String "text", raw """multi-line"""
nullable String? — may hold null
fun main() {
    val count: Int = 10
    val population = 1_400_000_000L
    val price = 99.5
    val grade = 'A'
    val ok = true
    val city: String? = null             // nullable type

    println("$count $population $price $grade $ok")
    println(city?.length ?: "no city")   // safe call + elvis operator
    println("42".toInt() + 1)
    println(7 / 2)
    println(7 / 2.0)
    println(Int.MAX_VALUE)
    println(price.toInt())
}

Output:

10 1400000000 99.5 A true
no city
43
3
3.5
2147483647
99

⚠️ Common error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver — handle the null case with ?., ?: or an if (x != null) check.

4. Operators

Arithmetic + - * / %, comparison == != < > <= >= (== compares content, === compares references), logical && || !, ranges .., until, downTo, step, membership in, null-safety ?. ?: !!, and bitwise functions and or xor shl shr.

fun main() {
    val a = 17
    val b = 5
    println("${a / b} ${a % b} ${a.toDouble() / b}")
    println("${a > b && b > 0} ${a in 10..20} ${'k' in "kotlin"}")
    println("${6 and 3} ${6 or 3} ${6 xor 3} ${1 shl 10}")
    val s1 = "hi"
    val s2 = String(charArrayOf('h', 'i'))
    println("${s1 == s2} ${s1 === s2}")
}

Output:

3 2 3.4
true true true
2 7 5 1024
true false

⚠️ Common error: using !! everywhere — it throws NullPointerException if the value is null. Prefer ?. and ?:.

5. Conditional Statements

if and when are expressions — they return values.

fun grade(marks: Int): String = if (marks >= 90) "A" else if (marks >= 75) "B" else "C"

fun describe(x: Any): String = when (x) {
    0 -> "zero"
    in 1..9 -> "small number"
    is String -> "string of length ${x.length}"
    is List<*> -> "list of ${x.size}"
    else -> "something else"
}

fun main() {
    println(grade(82))
    println(describe(5))
    println(describe("kotlin"))
    println(describe(listOf(1, 2)))
    val temp = 31
    val feel = when {
        temp > 35 -> "hot"
        temp > 25 -> "warm"
        else -> "cool"
    }
    println(feel)
}

Output:

B
small number
string of length 6
list of 2
warm

⚠️ Common error: a when used as an expression must be exhaustive — add an else branch.

6. Loops

fun main() {
    for (i in 1..5) print("$i ")
    println()
    for (i in 10 downTo 0 step 3) print("$i ")
    println()
    for (i in 0 until 3) print("$i ")
    println()

    val langs = listOf("kotlin", "java", "swift")
    for ((index, lang) in langs.withIndex()) println("$index: $lang")

    var n = 1
    while (n < 100) n *= 3
    println("n = $n")

    repeat(3) { print("hi ") }
    println()

    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (i * j == 4) break@outer
            print("${i * j} ")
        }
    }
    println()
}

Output:

1 2 3 4 5 
10 7 4 1 
0 1 2 
0: kotlin
1: java
2: swift
n = 243
hi hi hi 
1 2 3 2 

⚠️ Common error: 1..n includes n. To loop over indices of a list use 0 until list.size or list.indices.

7. Functions

fun add(a: Int, b: Int = 10): Int = a + b                 // default parameter, single-expression body

fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"

fun sum(vararg nums: Int): Int = nums.sum()

fun String.isPalindrome(): Boolean {                       // extension function
    val clean = lowercase().filter { it.isLetterOrDigit() }
    return clean == clean.reversed()
}

fun applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))     // higher-order function

tailrec fun factorial(n: Long, acc: Long = 1): Long =      // tail recursion
    if (n <= 1) acc else factorial(n - 1, acc * n)

fun main() {
    println("${add(5)} ${sum(1, 2, 3, 4)} ${greet(greeting = "Namaste", name = "Ravi")}")
    println("${"Madam".isPalindrome()} ${"Kotlin".isPalindrome()}")
    val square = { n: Int -> n * n }                       // lambda
    println("${applyTwice(3, square)} ${applyTwice(5) { it + 1 }} ${factorial(15)}")
}

Output:

15 10 Namaste, Ravi!
true false
81 7 1307674368000

⚠️ Common error: Unresolved reference when calling an extension function from another file — import it (import com.example.utils.isPalindrome).

8. Arrays & Data Structures

Kotlin separates read-only collections (List, Set, Map) from mutable ones (MutableList, ...).

fun main() {
    val nums = listOf(5, 3, 8, 1, 9)
    println("${nums.sorted()} ${nums.max()} ${nums.sum()} ${nums.average()}")
    println("${nums.filter { it % 2 == 1 }} ${nums.map { it * 2 }} ${nums.first { it > 4 }}")
    println("${nums.any { it > 8 }} ${nums.count { it > 3 }} ${nums.take(2)} ${nums.reversed()}")

    val names = mutableListOf("Ravi", "Asha")
    names.add("Neha")
    names.sortBy { it }
    println(names)

    val ages = mutableMapOf("asha" to 21, "ravi" to 23)
    ages["neha"] = 22
    println("${ages["asha"]} ${ages.getOrDefault("john", 0)} ${ages.keys}")

    val words = "to be or not to be".split(" ")
    println(words.groupingBy { it }.eachCount())

    val set = setOf(3, 1, 3, 2)
    val arr = intArrayOf(4, 2, 7)
    val grid = Array(2) { IntArray(3) }
    grid[1][2] = 9
    println("$set ${arr.sum()} ${grid[1].toList()}")
}

Output:

[1, 3, 5, 8, 9] 9 26 5.2
[5, 3, 1, 9] [10, 6, 16, 2, 18] 5
true 3 [5, 3] [9, 1, 8, 3, 5]
[Asha, Neha, Ravi]
21 0 [asha, ravi, neha]
{to=2, be=2, or=1, not=1}
[3, 1, 2] 13 [0, 0, 9]

⚠️ Common error: Unresolved reference: add on a listOf(...) — read-only lists have no add. Use mutableListOf.

9. Object-Oriented Programming

Classes are final by default; mark them open to allow inheritance.

interface Shape {
    fun area(): Double
    val name: String get() = "shape"          // property with a default getter
}

open class Account(val owner: String, balance: Double) {
    var balance = balance
        private set                           // readable outside, writable only inside

    open fun deposit(amount: Double) {
        require(amount > 0) { "Amount must be positive" }
        balance += amount
    }
    override fun toString() = "$owner: $balance"
}

class Savings(owner: String, balance: Double, private val rate: Double) : Account(owner, balance) {
    fun addInterest() = deposit(balance * rate)
}

data class Point(val x: Int, val y: Int)       // equals, hashCode, toString, copy for free

class Circle(private val r: Double) : Shape {
    override fun area() = Math.PI * r * r
    override val name = "circle"
}

object Config {                                // singleton
    const val VERSION = "1.0"
}

sealed class Result {                          // restricted class hierarchy
    data class Success(val data: String) : Result()
    data class Error(val message: String) : Result()
}

fun render(r: Result) = when (r) {             // no else needed: sealed is exhaustive
    is Result.Success -> "OK: ${r.data}"
    is Result.Error -> "Failed: ${r.message}"
}

fun main() {
    val acc = Savings("Asha", 1000.0, 0.05)
    acc.deposit(1000.0)
    acc.addInterest()
    println(acc)
    val p = Point(1, 2)
    println("$p ${p.copy(y = 5)} ${p == Point(1, 2)}")
    println("${Circle(1.0).name} ${"%.2f".format(Circle(1.0).area())} ${Config.VERSION}")
    println("${render(Result.Success("data loaded"))} | ${render(Result.Error("timeout"))}")
}

Output:

Asha: 2100.0
Point(x=1, y=2) Point(x=1, y=5) true
circle 3.14 1.0
OK: data loaded | Failed: timeout

⚠️ Common error: This type is final, so it cannot be inherited from — add open to the parent class (and to methods you want to override).

10. Advanced Concepts

Generics:

class Box<T>(val value: T) {
    fun <R> map(f: (T) -> R): Box<R> = Box(f(value))
}

fun <T : Comparable<T>> maxOf(a: T, b: T): T = if (a > b) a else b

fun main() {
    val b = Box(21).map { it * 2 }.map { "answer=$it" }
    println("${b.value} ${maxOf("apple", "mango")} ${maxOf(3, 9)}")
}
answer=42 mango 9

Scope functions — let, apply, also, run, with:

data class User(var name: String = "", var age: Int = 0)

fun main() {
    val user = User().apply { name = "Neha"; age = 22 }      // configure an object
    val email: String? = "neha@example.com"
    email?.let { println("sending mail to $it") }            // run only if not null
    val summary = with(user) { "$name is $age" }
    println(summary)
}
sending mail to neha@example.com
Neha is 22

Coroutines (add org.jetbrains.kotlinx:kotlinx-coroutines-core) — lightweight concurrency for network calls and background work:

import kotlinx.coroutines.*

suspend fun fetchUser(id: Int): String {
    delay(100)                      // non-blocking wait (e.g. a network call)
    return "user$id"
}

fun main() = runBlocking {
    val a = async { fetchUser(1) }
    val b = async { fetchUser(2) }
    println("${a.await()} ${b.await()}")    // both run concurrently: ~100 ms total
}

On Android, coroutines run in viewModelScope/lifecycleScope; Flow streams values over time.

Exceptions work like Java's, but try is an expression and there are no checked exceptions:

fun main() {
    val n = try { "12x".toInt() } catch (e: NumberFormatException) { -1 }
    println(n)
    println("12x".toIntOrNull() ?: 0)
}
-1
0

Android basics: an app is made of Activities/Fragments (screens), UI is built with Jetpack Compose (@Composable functions) or XML layouts, state lives in a ViewModel, and data comes from Room (database) or Retrofit (network).

@Composable
fun Counter() {
    var count by remember { mutableStateOf(0) }
    Button(onClick = { count++ }) {
        Text("Clicked $count times")
    }
}

11. Examples with Output

Example 1 — Word frequency, top 3

fun main() {
    val text = "the cat and the hat and the bat"
    text.split(" ")
        .groupingBy { it }.eachCount()
        .entries.sortedWith(compareByDescending<Map.Entry<String, Int>> { it.value }.thenBy { it.key })
        .take(3)
        .forEach { println("${it.key}: ${it.value}") }
}
the: 3
and: 2
bat: 1

Example 2 — Two Sum with a HashMap

fun twoSum(nums: IntArray, target: Int): Pair<Int, Int>? {
    val seen = HashMap<Int, Int>()
    nums.forEachIndexed { i, x ->
        seen[target - x]?.let { return it to i }
        seen[x] = i
    }
    return null
}

fun main() {
    println(twoSum(intArrayOf(2, 7, 11, 15), 9))
}
(0, 1)

Example 3 — Data class list processing

data class Student(val name: String, val dept: String, val marks: Int)

fun main() {
    val students = listOf(Student("Asha", "CSE", 91), Student("Ravi", "ECE", 78), Student("Neha", "CSE", 85))
    val avgByDept = students.groupBy { it.dept }.mapValues { (_, s) -> s.map { it.marks }.average() }
    println(avgByDept)
    println(students.maxBy { it.marks }.name)
}
{CSE=88.0, ECE=78.0}
Asha

12. Practice Problems

  1. Read a number with readln().toInt() and print whether it's prime.
  2. Write an extension fun Int.isEven() and fun String.wordCount().
  3. Model a library with data class Book and a Library class (add, borrow, return, search by author).
  4. Use a sealed class to represent network states (Loading, Success, Error) and render each.
  5. Process a list of transactions: total per category, biggest expense, monthly average.
  6. Fetch two "users" concurrently with coroutines (async + delay).
  7. Build a counter and a to-do list screen in Jetpack Compose.
  8. Solve the logic of Two Sum and Valid Parentheses in Kotlin (submit in Java/C++/Python on Codify).

13. Interview Questions

1. val vs var? val is a read-only reference (assigned once); var can be reassigned. The object a val points to can still be mutable.

2. How does Kotlin's null safety work? Types are non-null by default; String? may be null and must be handled with ?., ?:, !! or a null check — avoiding most NullPointerExceptions at compile time.

3. What is a data class? A class for holding data; the compiler generates equals, hashCode, toString, copy and componentN (destructuring).

4. What are extension functions? Functions added to an existing type without inheriting from it (fun String.shout() = uppercase()), resolved statically.

5. object vs companion object? object declares a singleton; a companion object is a singleton tied to a class, used for factory methods and constants (like Java static members).

6. What is a sealed class? A class whose subclasses are all known at compile time, so when over it is exhaustive — great for states and results.

7. Coroutines vs threads? Coroutines are lightweight, suspendable computations managed by Kotlin; thousands can run on a few threads. suspend functions pause without blocking a thread.

8. lateinit vs by lazy? lateinit var is a non-null property initialised later (mutable, no primitives); val x by lazy { } computes the value on first access and caches it.

9. Why are classes final by default? To prevent accidental inheritance problems (fragile base class); you opt in with open.

10. == vs ===? == checks structural equality (equals); === checks referential equality (same object).

14. Cheat Sheet & References

Basics

val x = 5; var y = 10; const val MAX = 100
println("x = $x, sum = ${x + y}")
val n = readln().toInt(); val parts = readln().split(" ").map { it.toInt() }
val s: String? = null; s?.length ?: 0

Control flow

val max = if (a > b) a else b
when (x) { 1, 2 -> "low"; in 3..9 -> "mid"; else -> "high" }
for (i in 0 until n) { } for (i in n downTo 1 step 2) { }
for ((i, v) in list.withIndex()) { }
repeat(3) { }

Functions

fun add(a: Int, b: Int = 0) = a + b
fun String.shout() = uppercase() + "!"
val sq = { x: Int -> x * x }
list.forEach { println(it) }

Collections

val l = listOf(1, 2); val ml = mutableListOf(1); ml.add(2)
val m = mapOf("a" to 1); val mm = mutableMapOf<String, Int>(); mm["b"] = 2
list.filter { it > 0 }.map { it * 2 }.sum()
list.sortedBy { it.age }; list.groupBy { it.dept }; list.associateBy { it.id }
list.firstOrNull { it > 5 }; list.any { }; list.all { }; list.count { }

Classes

class User(val name: String, var age: Int)
data class Point(val x: Int, val y: Int)
open class A { open fun f() {} }; class B : A() { override fun f() {} }
object Singleton { }
sealed class State { object Loading : State() }

Coroutines

suspend fun load(): String { delay(100); return "x" }
runBlocking { val a = async { load() }; println(a.await()) }
viewModelScope.launch { }

Official documentation