Kotlin Reference
0. Basics
0.1 Hello World
fun main() {
// println adds a newline
println("Hello, World!")
}
TERMINAL OUTPUT
Hello, World!
0.2 Building & Running
Kotlin targets the JVM. Use kotlinc to
compile.
# Compile and run
kotlinc main.kt -include-runtime -d main.jar
java -jar main.jar
TERMINAL OUTPUT
Hello, World!
0.3 Comments
// Single-line comment
/* Multi-line
comment block */
/** KDoc documentation comment */
TERMINAL OUTPUT
(No output)
0.4 Imports
import kotlin.math.*
import java.io.File
import kotlinx.coroutines.*
TERMINAL OUTPUT
(No output)
0.5 Exit Codes
import kotlin.system.exitProcess
fun main() {
// Exit with status 1
exitProcess(1)
}
TERMINAL OUTPUT
(Process exits with status 1)
0.6 Error Handling
try {
val x = 10 / 0
} catch (e: ArithmeticException) {
println("Caught: ${e.message}")
} finally {
println("Cleanup")
}
TERMINAL OUTPUT
Caught: / by zero
Cleanup
1. Environment & Time
1.1 Variable Declaration
val immutable = 10 // Read-only
var mutable = 20 // Mutable
const val PI = 3.14 // Compile-time constant
TERMINAL OUTPUT
(No output)
1.2 Integer Types
val i: Int = 1000
val l: Long = 1000L
val b: Byte = 1
val u: UInt = 10u // Unsigned (Kotlin 1.5+)
TERMINAL OUTPUT
(No output)
1.3 Casting
val s = "123"
val i = s.toInt()
val d = i.toDouble()
// Safe cast (returns null if fails)
val obj: Any = "Hello"
val str = obj as? String
TERMINAL OUTPUT
(No output)
1.4 Truthiness
Kotlin does not have implicit truthiness. Only
Boolean values work in if.
val x = 1
// if (x) { ... } // Error: Type mismatch
if (x != 0) { println("True") }
TERMINAL OUTPUT
True
1.5 Environment Vars
val path = System.getenv("PATH")
TERMINAL OUTPUT
(No output)
1.6 Time
import java.time.Instant
import java.time.format.DateTimeFormatter
val now = Instant.now()
println(now.toString()) // ISO-8601
val ms = System.currentTimeMillis()
TERMINAL OUTPUT
2024-05-16T12:00:00Z (example)
2. Operators & Regex
2.1 Arithmetic/Logic
val a = 10 / 3 // 3
val b = 10 % 3 // 1
val c = true && false
val d = true || false
TERMINAL OUTPUT
(No output)
2.2 Regex
val regex = """\d+""".toRegex()
val match = regex.find("price: 100")
if (match != null) {
println(match.value)
}
TERMINAL OUTPUT
100
3. Argument Parsing
3.1 CLI Argument Parsing
fun main(args: Array<String>) {
if (args.isNotEmpty()) {
println("First arg: ${args[0]}")
}
}
TERMINAL OUTPUT
(Depends on input)
4. Functions & Memory
4.1 Declaration/Returns
fun add(a: Int, b: Int = 0): Int {
return a + b
}
// Single-expression function
fun multiply(a: Int, b: Int) = a * b
TERMINAL OUTPUT
(No output)
4.2 References/Pointers
JVM-based memory model. Objects are passed by reference. Kotlin uses explicit nullability.
var nullable: String? = null
val length = nullable?.length ?: 0 // Elvis operator
fun modify(list: MutableList<Int>) {
list.add(1)
}
TERMINAL OUTPUT
(No output)
5. Loops & Iteration
5.1 Basic Loops
for (i in 1..3) { println(i) } // Inclusive range
for (i in 0 until 3) { println(i) } // Exclusive range
var x = 0
while (x < 2) { x++ }
TERMINAL OUTPUT
1
2
3
0
1
2
5.2 Break/Continue
for (i in 1..5) {
if (i == 2) continue
if (i == 4) break
println(i)
}
TERMINAL OUTPUT
1
3
5.3 Iterating Collections
val items = listOf("a", "b")
for (item in items) { println(item) }
items.forEachIndexed { index, value ->
println("$index: $value")
}
TERMINAL OUTPUT
a
b
0: a
1: b
6. Strings & Files
6.1 Manipulation
val name = "Kotlin"
val s = "Hello, $name!" // Template
val multi = """
Line 1
Line 2
""".trimIndent()
TERMINAL OUTPUT
(No output)
6.2 Path Joining
import java.io.File
import java.nio.file.Paths
val p1 = File("dir", "file.txt")
val p2 = Paths.get("dir", "file.txt")
TERMINAL OUTPUT
(No output)
6.3 Streaming I/O
import java.io.File
File("data.bin").inputStream().use { input ->
val buffer = ByteArray(4096)
var bytesRead = input.read(buffer)
while (bytesRead != -1) {
// Process buffer
bytesRead = input.read(buffer)
}
}
TERMINAL OUTPUT
(No output)
6.4 Read to Memory
import java.io.File
val text = File("file.txt").readText()
val bytes = File("file.txt").readBytes()
TERMINAL OUTPUT
(No output)
7. Binary & Bitwise
7.1 Allocation/Packing
import java.nio.ByteBuffer
val buffer = ByteBuffer.allocate(12)
buffer.putInt(42)
buffer.putDouble(3.14)
buffer.flip()
TERMINAL OUTPUT
(No output)
7.2 Bitwise Ops
val a = 0b1010 and 0b1100 // AND
val b = 0b1010 or 0b1100 // OR
val c = 1 shl 3 // Shift Left (8)
val d = 8 shr 1 // Shift Right (4)
TERMINAL OUTPUT
(No output)
7.3 Hex Conversion
val hex = 255.toString(16) // "ff"
val i = "ff".toInt(16) // 255
TERMINAL OUTPUT
(No output)
8. Collections & JSON
8.1 Lists/Maps/Sets
val list = listOf(1, 2) // Immutable
val mList = mutableListOf(1, 2) // Mutable
val map = mapOf("a" to 1)
val set = setOf(1, 1, 2) // {1, 2}
TERMINAL OUTPUT
(No output)
8.2 JSON Parsing
(Using standard org.json or similar logic
common in references)
// Serialization usually requires a library like kotlinx.serialization
// val json = Json.encodeToString(data)
TERMINAL OUTPUT
(No output)
9. Systems & Networking
9.1 TCP
import java.net.ServerSocket
import java.net.Socket
// Server
// val srv = ServerSocket(8080).accept()
// Client
Socket("localhost", 8080).use { s ->
s.getOutputStream().write("hello".toByteArray())
}
TERMINAL OUTPUT
(No output)
9.2 UDP
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
val socket = DatagramSocket()
val buf = "ping".toByteArray()
val packet = DatagramPacket(buf, buf.size, InetAddress.getByName("localhost"), 8080)
socket.send(packet)
TERMINAL OUTPUT
(No output)
9.3 Concurrency
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(10)
println("Task")
}
println("Main")
}
TERMINAL OUTPUT
Main
Task
9.4 SQLite
import java.sql.DriverManager
val conn = DriverManager.getConnection("jdbc:sqlite::memory:")
val stmt = conn.createStatement()
stmt.execute("CREATE TABLE t(id INT)")
stmt.executeUpdate("INSERT INTO t VALUES (42)")
val rs = stmt.executeQuery("SELECT id FROM t")
if (rs.next()) println(rs.getInt(1))
TERMINAL OUTPUT
42