⬅ Previous TopicJavaScript Cheat Sheet
Next Topic ⮕PHP Cheat Sheet
Kotlin has two types of variables: val
(immutable) and var
(mutable).
val name: String = "Kotlin"
var age: Int = 25
Kotlin has two types of variables: val
(immutable) and var
(mutable).
val name: String = "Kotlin"
var age: Int = 25
Explicit type declaration is optional when the compiler can infer it.
val message = "Hello"
var count = 10
Kotlin enforces null safety at compile time using nullable types.
var name: String? = null
Embed variables and expressions in strings using $
and ${}
.
val name = "World"
println("Hello, $name!")
val max = if (a > b) a else b
when (x) {
1 -> println("One")
else -> println("Other")
}
for (i in 1..5) {
println(i)
}
fun greet(name: String): String {
return "Hello, $name"
}
fun greet(name: String = "Guest") {
println("Hello, $name")
}
fun main() {
greet() // uses default
greet(name = "Sam") // named argument
}
val sum = { a: Int, b: Int -> a + b }
fun operate(x: Int, y: Int, op: (Int, Int) -> Int): Int = op(x, y)
inline fun operate(a: Int, b: Int, func: (Int, Int) -> Int): Int {
return func(a, b)
}
class Person(val name: String) {
fun greet() = println("Hello, $name")
}
class Person(val name: String) {
constructor(name: String, age: Int): this(name)
}
open class Animal {
open fun sound() = println("...")
}
class Dog: Animal() {
override fun sound() = println("Bark")
}
Modifiers: public
, internal
, protected
, private
private class Secret
data class User(val name: String, val age: Int)
object Logger {
fun log(msg: String) = println(msg)
}
val numbers = listOf(1, 2, 3)
val mutableNumbers = mutableListOf(1, 2, 3)
val uniqueItems = setOf("a", "b")
val mapping = mapOf("key" to "value")
val nums = listOf(1, 2, 3, 4)
val evens = nums.filter { it % 2 == 0 }
val doubled = nums.map { it * 2 }
val total = nums.reduce { acc, i -> acc + i }
listOf
, setOf
, and mapOf
create immutable collections. Use mutableListOf
, etc. for mutable ones.
fun String.shout(): String = this.uppercase() + "!"
println("hello".shout())
val name: String? = null
val length = name?.length // Safe call
val len = name?.length ?: 0 // Elvis operator
val forced = name!!.length // Not-null assertion
name?.let { println(it) } // let
name?.run { println(this) } // run
name?.also { println(it) } // also
name?.apply { println(this) } // apply
Prefer val
over var
and avoid mutation.
val f: (Int, Int) -> Int = { x, y -> x + y }
fun counter(): () -> Int {
var count = 0
return { ++count }
}
"kotlin".reversed()
"abc".uppercase()
for (i in 1..5) { }
for (j in 5 downTo 1 step 2) { }
val (a, b) = Pair(1, 2)
val pair = Pair("x", 1)
val triple = Triple("x", 1, true)
try {
val result = riskyOp()
} catch (e: Exception) {
println("Error: ${e.message}")
} finally {
println("Done")
}
class MyException(message: String): Exception(message)
suspend fun fetchData(): String {
delay(1000)
return "Data"
}
CoroutineScope(Dispatchers.IO).launch {
val data = fetchData()
println(data)
}
Dispatchers.Default
Dispatchers.IO
Dispatchers.Main
typealias ClickHandler = (Int) -> Unit
sealed class Result
class Success(val data: String): Result()
class Error(val exception: Throwable): Result()
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
@Deprecated("Use newFunc")
fun oldFunc() { }
class Box(val item: T)
fun demo(x: Any) {
if (x is String) {
println(x.length) // smart cast to String
}
}