Skip to content

Instantly share code, notes, and snippets.

@audreyfeldroy
Last active May 23, 2024 03:12
Show Gist options
  • Save audreyfeldroy/d058c1b86e18b7dbaa9e4a1907e7b10b to your computer and use it in GitHub Desktop.
Save audreyfeldroy/d058c1b86e18b7dbaa9e4a1907e7b10b to your computer and use it in GitHub Desktop.
Audrey's Kotlin for Developers Cheatsheet

Variables

Declare var for a mutable variable:

var name = "Mommy"
name = "Uma"

Declare val for a read-only constant:

val pi = 3.14

Increment and decrement operators:

var toyCount = 4
toyCount++
toyCount--

Double for decimal values:

var starValue: Double = 0.1

Boolean for true/false values:

var isPlaying = true

Comments

// This is a single-line comment

/*
This is a multi-line comment
*/

/**
 * This is a KDoc documentation comment
 */

Functions

fun greeting(): String {
    return "Hello!"
}

println(greeting())

Function with KDoc documentation:

fun add(a: Int, b: Int): Int {
    /**
     * Adds two numbers together.
     *
     * @param a The first number to add.
     * @param b The second number to add.
     * @return The sum of the two numbers.
     */
    return a + b
}

Classes

class Person(var name: String)

val person = Person("John")
person.name = "Daddy"

Inheritance

The open keyword is required to allow inheritance. By default, classes are final and cannot be inherited from.

open class Person(var name: String)

class Student(name: String, var grade: Int) : Person(name)

val student = Student("Daddy", 5)
student.name = "Uma"
student.grade = 6

Data Classes

A data class is a class that only holds data, and has no behavior.

data class Person(var name: String)

val person = Person("Mommy")
person.name = "Uma"

Collections

val numbers = mutableListOf(1,2,3)
numbers.add(4)

val numsSet = setOf(1,2,3)
println(numsSet.contains(2))

Control Flow

fun max(a: Int, b: Int): Int {
    return if (a > b) a else b
}

val result = max(1, 2)

Null Safety

var name: String? = null
name = "John"

Extensions

fun String.initials(): String {
    return this.split(" ").map { it.first() }.joinToString("")
}

val name = "John Doe"
println(name.initials())

Lambdas

val numbers = listOf(1,2,3)
numbers.forEach { println(it) }

Higher-Order Functions

fun sum(a: Int, b: Int): Int {
    return a + b
}

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

val result = calculate(1, 2, ::sum)

Generics

class Box<T>(t: T) {
    var value = t
}

val box = Box(1)

Coroutines

fun main() = runBlocking {
    launch {
        delay(1000L)
        println("World!")
    }
    println("Hello,")
}

Android

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Resources

Credits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment