Kotlin Cheatsheet
Input, Output & Parsing
Use this Kotlin reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Reading stdin
fun main() { val line = readln() // String, throws on EOF (Kotlin 1.6+) val maybe = readlnOrNull() // String? — null at EOF val nums = readln().trim().split(" ").map { it.toInt() } val (a, b) = readln().split(" ").map { it.toInt() } println(nums.sum()) }
readLine() is the older nullable spelling; prefer readln()/readlnOrNull(). Parse defensively with toIntOrNull() when input isn't trusted.
Read everything at once:
val all = generateSequence(::readlnOrNull).toList() // all lines val text = System.`in`.bufferedReader().readText() // one string
Fast IO (large inputs)
readln() + split allocates per token; for big inputs use a buffered reader + tokenizer:
import java.io.BufferedReader import java.io.InputStreamReader import java.util.StringTokenizer fun main() { val br = BufferedReader(InputStreamReader(System.`in`)) val (n, m) = br.readLine().split(" ").map { it.toInt() } val st = StringTokenizer(br.readLine()) val xs = IntArray(n) { st.nextToken().toInt() } val out = StringBuilder() // batch output — never println in a loop for (x in xs) out.append(x * 2).append('\n') print(out) }
Writing output & formatting
println("plain") // stdout + newline print("no newline") System.err.println("diagnostics") // stderr "%.2f".format(3.14159) // "3.14" String.format("%05d", 42) // "00042" "%,d".format(1234567) // "1,234,567" (locale-dependent) val s = buildString { append("a"); appendLine("b") }
| Format | Meaning |
|---|---|
%d, %05d | int, zero-padded width 5 |
%.3f, %e | fixed decimals, scientific |
%s, %-10s | string, left-justified width 10 |
%x, %o, %b | hex, octal, boolean |
Number ↔ string: x.toString(2) (binary), "ff".toInt(16), Integer.toBinaryString(x).
Files (kotlin.io + java.nio)
import java.io.File val text = File("data.txt").readText() val lines = File("data.txt").readLines() // List<String> File("data.txt").useLines { seq -> // lazy, auto-closes seq.filter { it.isNotBlank() }.count() } File("out.txt").writeText("hello\n") File("out.txt").appendText("more\n") File("big.txt").bufferedWriter().use { w -> // `use` = try-with-resources w.write("line"); w.newLine() } // java.nio.file for paths/dirs import java.nio.file.* Files.createDirectories(Path.of("build/reports")) Files.exists(Path.of("data.txt")) File("dir").walk().filter { it.extension == "kt" }.toList()
Parsing patterns
// key=value pairs val cfg = File("app.cfg").readLines() .filter { "=" in it } .associate { it.substringBefore("=").trim() to it.substringAfter("=").trim() } // CSV-ish line val cols = line.split(",").map { it.trim() } // Regex extraction val m = Regex("""(\d{4})-(\d{2})-(\d{2})""").find("due 2026-07-05") val (y, mo, d) = m!!.destructured Regex("""\d+""").findAll(text).map { it.value.toInt() }.toList()
Raw strings ("""...""") keep regexes readable — no double-escaping backslashes.