You are on page 1of 2

Kotlin Cheat Sheet and Quick Reference

val more = if (x > y) x else y // more == 100 // Another way to test membership
Declaring Variables val less = if (x < y) { val isBobThere2 = immutableList.contains("Bob")
var mutable: Int = 1 println("x is smaller.") val name: String = immutableList[0] // Access by index
mutable = 2 // OK: You can reassign a var. x // The last expression is the block’s value valMutableList[1] = "Bart" // Update item in list
val immutable: Double = 2.0 } else { // immutableList[1] = “Bart" // Error: Can't change
// immutable = 3.0 // Error: You can't reassign a val! println("y is smaller.") valMutableList.add(2, "Ellen") // Add item at index
var greeting = "Hello, world!" // Inferred as String y // Delete by index
var catchphrase: String? = null // Nullable type } val removedPerson = valMutableList.removeAt(1)
catchphrase = "Hey, what's up, everybody?" // Delete by value
val wasRemoved = valMutableList.remove("Bart")
// You can change the contents of a val mutable
Control Flow: when expression
Nullable Types // Using when to choose different paths
collection, but you CAN’T reassign it:
// You can change the contents of a var mutable
var mutable: Int = 1 val year = 2010 collection, and you CAN reassign it:
mutable = 2 // OK: You can reassign a var. when (year) { varMutableList[0] = "Ellen"
val immutable: Double = 2.0 2010 -> print("Froyo") varMutableList = mutableListOf("Gemma", "Harry")
// immutable = 3.0  // Error: You can't reassign a val! 2011 -> print("Ice Cream Sandwich")
var greeting = "Hello, world!" // Inferred as String 2008, 2009 -> print("The early days")
var catchphrase: String? = null // Nullable type in 2012..2015 -> {
catchphrase = "Hey, what's up, everybody?"   println("Jellybean through Marshmallow,")
var name: String? = null // Can hold a String or null   println("when things got interesting.") Collections: Map
}
// Safe cast operator ?. val immutableMap = mapOf("name" to "Kirk", "rank" to
else -> println("Some other era")
// length1 contains name's length if name isn't null; "captain")
}
null otherwise val mutableMap = mutableMapOf("name" to "Picard",
// Using when to set a value
val length1: Int? = name?.length "rank" to "captain")
val androidEra = when (year) { // Is this key in the map?
2010 -> "Froyo"
// Elvis operator ?: val hasRankKey = immutableMap.containsKey("rank")
2011 -> "Ice Cream Sandwich"
// length1 contains name's length if name isn't null; 0 // Is this value in the map?
2008, 2009 -> "The early days"
otherwise val hasKirkValue = immutableMap.containsValue("Kirk")
in 2012..2015 -> {
val length2: Int = name?.length ?: 0 // Access by key, returns nullable
  print("Jellybean through Marshmallow")
// The Elvis operator can also execute statements in val name: String? = immutableMap["name"]
  // The last expression is the block’s value
the case of null values. // Update value for key
  "When things got interesting"
val length3 = name?.length ?: return mutableMap["name"] = "Janeway"
} // Add new key and value
else -> "Some other era"
// Non-null assertion operator !! mutableMap["ship"] = "Voyager"
}
name = "Francis" mutableMap.remove("rank") // Delete by key
// Using when with conditionals to set a value
val length4: Int = name!!.length // Works if name isn't // Delete by key and value
val catsOwned = 2
null; crashes otherwise mutableMap.remove("ship", "Voyager")
val dogsOwned = 1 // Won't work, value doesn't match
val judgement = when {
// Smart casts and checking for null mutableMap.remove("name", "Spock")
catsOwned == 0 -> "No cats"
var nonNullableAuthor: String catsOwned < 0 -> {
var nullableAuthor: String?   print("Call the cat police!")
if (name != null) { // Checking for null   // The last expression is the block’s value
nonNullableAuthor = name // Smart cast to String   "Owes someone some cats"
} else { } Collections: Set
nullableAuthor = name // Smart cast to String? catsOwned == 1 && dogsOwned == 1 -> // Sets ignore duplicate items, so immutableSet has 2
} "Seeking balance" items: "chocolate" and "vanilla"
catsOwned > 0 && catsOwned < 3 -> “Yay cats!” val immutableSet = setOf<String>("chocolate",
else -> “Cat Nirvana" "vanilla", "chocolate")
Control Flow: if expression } val mutableSet = mutableSetOf("butterscotch",
"strawberry")
// Using if to choose different paths // One way to test membership
var condition = true val hasChocolate1 = "chocolate" in immutableSet
if (condition) { // Another way to test membership
// If condition is true, this gets executed
} else { Collections: List val hasChocolate2 = immutableSet.contains("chocolate")
mutableSet.add("green tea") // Add item
// If condition is false, this gets executed val immutableList = listOf("Alice", "Bob") // Delete by value
} val valMutableList = mutableListOf("Carol", "Dave") val flavorWasRemoved = mutableSet.remove("strawberry")
// Using if to set a value var varMutableList = mutableListOf("Eve", "Frank")
val x = 100 // One way to test membership
val y = 1 val isBobThere1 = "Bob" in immutableList

Source: raywenderlich.com. Visit for more Android/Kotlin resources and tutorials! Version 1.0. Copyright 2018 Ray Wenderlich. All rights reserved.
Page 1
! of 2
Kotlin Cheat Sheet and Quick Reference
// Calling a function that accepts another function
Control Flow: loops val add = doMath(::total, 2, 3) class Sailor(var rank: String, var lastName: String) {
// Iterate over list or set val multiply = doMath(::product, 2, 3) // Class properties with accessors
for (item in listOrSet) { var fullName: String
get() = "$rank $lastName"
}
println(item)
Lambdas set(value) {
// Iterate over map // Lambda val (firstWord, remainder) = value.split(" ",
for ((key, value) in myMap) { val adder: (Int, Int) -> Int = { x, y -> x + y} limit = 2)
println("$key -> $value") // Lambda with single parameter: it keyword rank = firstWord
} val square: (Int) -> Int = { it * it} lastName = remainder
// Iterating over ranges // Passing a lambda to a function }
for (i in 0..10) {} // 0 to 10 val addWithLambda = doMath(adder, 2, 3) }
for (i in 0 until 10) {} // 0 to 9 // Subclassing: only open classes can be subclassed
for (i in 1..10 step 2) {} // 1, 3, 5, 7, 9 open class Crewmember(val name: String) {
for (i in 10 downTo 1) {} // 10 to 1
// while and do while Extensions // Only open methods can be overridden
open fun sayHello() = "Hello, I'm crewmember $name."
var x = 0 // Add the “fizzbuzz()”  function to the Int class }
while (x < 10) { fun Int.fizzBuzz(): String { // Subclassing
x++ return when { class Captain(name: String): Crewmember(name) {
println(x) this % 3 == 0 -> "fizz" override fun sayHello() = "Greetings! I am Captain
} this % 5 == 0 -> "buzz" $name."
do { this % 15 == 0 -> "fizzbuzz" }
x-- else -> this.toString()
println(x) }
} while (x > 0) }
println(6.fizzBuzz()) // Prints “fizz” Data Classes
println(8.fizzBuzz()) // Prints “8” // A data class is a structured data container
// with pre-defined toString() and other overrides
Functions // Add the “absValue” property to the Int class
val Int.absValue: Int data class Student(val name: String, var year: Int)
fun sayHi() { // A Unit function get() = abs(this) // name is a read-only property, year is mutable
println("Hello") println((-3).absValue) // Prints “3” val newStudent = Student("Siddartha", 1)
} // Data class with properties outside the constructor
// Function with parameters data class Professor(val name: String) {
fun sayHello(name: String) { Objects var isTenured: Boolean = false
println("Hello, $name!") // Only a single instance exists }
} // Takes the place of static utility classes val newProfessor = Professor("Snape")
// Function with default arguments object Constants { newProfessor.isTenured = true
fun sayFriendlyHello(name: String = "Friend") { const val baseUrl = “http://api.raywenderlich.com”
print("Hello, $name!") }
}
// Function with mix of regular and default arguments
Enum Classes
fun createCat(name: String = "Kitty", age: Int, Classes enum class Taste {
isSpayed: Boolean = false) { SWEET, SOUR, SALTY, BITTER, UMAMI
// Class basics
print("$name / $age / $isSpayed") }
class Spaceship(var name: String, val size: Int) {
} var speed: Int = 0
createCat(age = 1) // Using just the non-default val vinegarTaste: Taste = Taste.UMAMI
fun fly() {
argument // Iterating through an enum class
speed = 100
createCat("Fluffy", 2, true) // One way to call a for (flavor in Taste.values()) {
}
function print("Taste: ${flavor.ordinal}: ${flavor.name}")
fun isFlying(): Boolean {
// Calling a function with named arguments }
return speed > 0
createCat(age = 2, isSpayed = true, name = "Fluffy") }
// Function with parameters and return value // Companion object replaces static members
fun total(x: Int, y: Int): Int { companion object { Sealed Classes
return x + y fun newSpaceship(): Spaceship { // Like enum classes, but can make multiple instances
} return Spaceship("Falcon", 25) sealed class Shape {
// A function as a single expression } class Circle(val radius: Int): Shape()
fun product(x: Int, y: Int) = x * y } class Square(val sideLength: Int): Shape()
// A function that accepts another function } }
fun doMath(mathOperation: (Int, Int) -> Int, a: Int, b: val myShip = Spaceship("Enterprise", 150) val circle1 = Shape.Circle(3)
Int): Int { myShip.fly() val circle2 = Shape.Circle(42)
return mathOperation(a, b) val flying = myShip.isFlying() val square = Shape.Square(5)
}

Source: raywenderlich.com. Visit for more Android/Kotlin resources and tutorials! Version 1.0. Copyright 2018 Ray Wenderlich. All rights reserved.
Page 2
! of 2

You might also like