DEV Community

Lam
Lam

Posted on

Kotlin Cheat Sheet

ComponentN Functions

class Person(val name: String, val age: Int) {
    operator fun component1(): String {
        return name
    }

    operator fun component2(): Int {
        return age
    }
}
Enter fullscreen mode Exit fullscreen mode

References

val person = Person("Adam", 100)
val (name, age) = person

val pair = Pair(1, 2)
val (first, second) = pair

val coordinates = arrayOf(1, 2, 3)
val (x, y, z) = coordinates
Enter fullscreen mode Exit fullscreen mode

While Loops

while (x > 0) {
    x--
}

do {
    x--
} while (x > 0)
Enter fullscreen mode Exit fullscreen mode

Destructuring Declarations

{: .-two-column}

When Statements

when (direction) {
    NORTH -> {
        print("North")
    }
    SOUTH -> print("South")
    EAST, WEST -> print("East or West")
    "N/A" -> print("Unavailable")
    else -> print("Invalid Direction")
}
Enter fullscreen mode Exit fullscreen mode

For Loops

for (i in 0..10) { } // 1 - 10
for (i in 0 until 10) // 1 - 9
(0..10).forEach { }
for (i in 0 until 10 step 2) // 0, 2, 4, 6, 8
Enter fullscreen mode Exit fullscreen mode

If Statements

if (someBoolean) {
    doThing()
} else {
    doOtherThing()
}
Enter fullscreen mode Exit fullscreen mode

Inheritance & Implementation

open class Vehicle
class Car : Vehicle()

interface Runner {
    fun run()
}

class Machine : Runner {
    override fun run() {
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

Control Flow

Secondary Constructors

class Person(val name: String) {
    private var age: Int? = null

    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

// Above can be replaced with default params
class Person(val name: String, val age: Int? = null)
Enter fullscreen mode Exit fullscreen mode

Primary Constructor

class Person(val name: String, val age: Int)
val adam = Person("Adam", 100)
Enter fullscreen mode Exit fullscreen mode

Static Functions

class Fragment(val args: Bundle) {
    companion object {
        fun newInstance(args: Bundle): Fragment {
            return Fragment(args)
        }
    }
}

val fragment = Fragment.newInstance(args)
Enter fullscreen mode Exit fullscreen mode

Classes

Reference

Top comments (0)