Kotlin Cheat Sheet & Quick Reference
Kotlin Cheat Sheet & Quick Reference
A quick reference cheatsheet for Kotlin that includes usage, examples, and more.
# Introduction to Kotlin
main()
fun main() {
println("Greetings, QuickRef.ME!")
// Code goes here
}
The main() function is the starting point of every Kotlin program and must be included in the code before execution
Print statement
println("Greetings, earthling!")
print("Take me to ")
print("your leader.")
/*
Print:
Greetings, earthling!
Take me to your leader.
*/
Notes
/*
this
note
for
many
*/
Execution order
fun main() {
println("I will be printed first.")
println("I will be printed second.")
println("I will be printed third.")
}
var age = 25
age = 26
Immutable variables
// The following variables are assigned a literal value inside double quotes
// so the inferred type is String
String concatenation
String Templates
println(monument. capitalize())
// print: The Statue of Liberty
println(monument. length)
// print: 21
Character escape
print("\"Excellent!\" I cried. \"Elementary,\" said he.")
\t inserts a tab
\\ inserts a backslash
Arithmetic Operators
5 + 7 // 12
9 -2 // 7
8 *4 // 32
25 /5 // 5
31 % 2 // 1
Order of operations
5 + 8 *2 /4 -3 // 6
3 + (4 + 4) /2 // 7
4 *2 + 1 *7 // 15
3 + 18 /2 *1 // 12
6 -3 % 2 + 2 // 7
var batteryPercentage = 80
// long syntax
batteryPercentage = batteryPercantage + 10
Math library
if (morning) {
println("Rise and shine!")
}
// Print: Rise and shine!
Else-expression
if (rained) {
println("No need to water the plants today.")
} else {
println("The plant needs to be watered!")
}
// print: The plant needs watering!
Else-If expressions
var age = 65
if (age < 18 ) {
println("You are considered a minor")
} else if (age < 60) {
println("You are considered an adult")
} else {
println("You are considered senior")
}
var myAge = 19
var sisterAge = 11
var cousinAge = 11
Logical Operators
println(!humid)
// print: false
println(jacket && raining)
// print: true
println(humid || raining)
// print: true
Or operator:||
// true OR true
println(skipBreakfast || late) // true
// true OR false
println(late || checkEmails) // true
// false OR true
println(underslept || late) // true
// false OR false
println(checkEmails || underslept) // false
NOT operator
Evaluation order
Nested conditions
if (wellRested) {
println("Good luck today!")
if (studied) {
println("You should prepare for the exam!")
} else {
println("Spend a few hours studying before the exam!")
}
}
when (grade) {
"A" -> println("Great job!")
"B" -> println("Great job!")
"C" -> println("You passed!")
else -> println("Close! Be sure to prepare more next time!")
}
// print: Great job!
Range operator
if (height in 1..53) {
println("Sorry, you must be at least 54 inches to ride the coaster")
}
// Prints: Sorry, you must be at least 54 inches to ride the roller coaster
Equality Operators
var myAge = 22
var sisterAge = 21
Mutable List
Access List
Size Attribute
var worldContinents = listOf("Asia", "Africa", "North America", "South America", "Antarctica", "Europe",
"Australia")
println(worldContinents.size) // Prints: 7
List Manipulation
// The contains() function performs a read operation on any list and determines if the element exists
seas.add("Baltic Sea") // Error: cannot write to immutable list
// The add() function can only be called on mutable lists, so the code above throws an error
Immutable Sets
Mutable Sets
var womenInTech = mutableSetOf("Ada Lovelace", "Grace Hopper", "Radia Perlman", "Sister Mary Kenneth
println(companies.elementAt(3))
// Prints: Google
println(companies.elementAt(4))
// Returns and Error
println(companies.elementAtOrNull(4))
// Prints: null
Immutable Map
var averageTemp = mapOf("winter" to 35, "spring" to 60, "summer" to 85, "fall" to 55)
Mutable Mapping
var europeanDomains = mutableMapOf("Germany" to "de", "Slovakia" to "sk", "Hungary" to "hu", "Norway" to "no")
var oscarWinners = mutableMapOf("Parasite" to "Bong Joon-ho", "Green Book" to "Jim Burke", "The Shape Of Water
println(oscarWinners.keys)
// Prints: [Parasite, Green Book, The Shape Of Water]
println(oscarWinners.values)
// Prints: [Bong Joon-ho, Jim Burke, Guillermo del Toro]
println(oscarWinners["Parasite"])
// Prints: Bong Joon-ho
var worldCapitals = mutableMapOf("United States" to "Washington D.C.", "Germany" to "Berlin", "Mexico" to "Mex
worldCapitals.put("Brazil", "Brasilia")
println(worldCapitals)
// Prints: {United States=Washington D.C., Germany=Berlin, Mexico=Mexico City, France=Paris, Brazil=Brasilia}
worldCapitals.remove("Germany")
println(worldCapitals)
// Prints: {United States=Washington D.C., Mexico=Mexico City, France=Paris, Brazil=Brasilia}
# Function
Function
fun greet() {
println("Hey there!")
}
fun main() {
//Function call
greet() //Prints: Hey there!
}
Function Parameters
fun main() {
birthday("Oscar", 26)
//Prints: Happy birthday Oscar! You turn 25 today!
birthday("Amarah", 30)
//Prints: Happy birthday Amarah! You turn 30 today!
}
Default Parameters
fun main() {
favoriteLanguage("Manon")
//Prints: Hello, Manon. Your favorite programming language is Kotlin
favoriteLanguage("Lee", "Java")
//Prints: Hello, Lee. Your favorite programming language is Java
}
Named Parameters
fun findMyAge(currentYear: Int, birthYear: Int) {
var myAge = currentYear -birthYear
println("I am $myAge years old.")
}
fun main() {
findMyAge(currentYear = 2020, birthYear = 1995)
//Prints: I am 25 years old.
findMyAge(birthYear = 1920, currentYear = 2020)
//Prints: I am 100 years old.
}
Return Statement
//return statement
return area
}
fun main() {
var myArea = getArea(10, 8)
println("The area is $myArea.")
//Prints: The area is 80.
}
Function Literals
fun main() {
//Anonymous Function:
var getProduct = fun(num1: Int, num2: Int): Int {
return num1 *num2
}
println(getProduct(8, 3))
//Prints: 24
//Lambda Expression
var getDifference = { num1: Int, num2: Int -> num1 -num2 }
println(getDifference(10, 3))
//Prints: 7
}
# Class
Class Example
// Class
class Student {
var name = "Lucia"
var semester = "Fall"
var gpa = 3.95
}
fun main() {
var student = Student()
// Instance
println(student.name)
// Prints: Lucia
println(student.semester)
// Prints: Fall
println(student.gpa)
// Prints: 3.95
}
Primary Constructor
class Student(val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int)
fun main() {
var student = Student("Lucia", 3.95, "Fall", 2022)
println(student.name)
//Prints: Lucia
println(student.gpa)
//Prints: 3.95
println(student.semester)
//Prints: Fall
println(student.estimatedGraduationYear)
//Prints: 2022
}
Initialization Block
class Student(val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int) {
init {
println("$name has ${estimatedGraduationYear -2020} years left in college.")
}
}
fun main() {
var student = Student("Lucia", 3.95, "Fall", 2022)
//Prints: Lucia has 2 years left in college.
}
Member Function
class Student(val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int) {
init {
println("$name has ${estimatedGraduationYear -2020} years left in college.")
}
//member function
fun calculateLetterGrade(): String {
return when {
gpa >= 3.0 -> "A"
gpa >= 2.7 -> "B"
gpa >= 1.7 -> "C"
gpa >= 1.0 -> "D"
else -> "E"
}
}
}
//When the instance is created and the function is called, the when expression will be executed and return the
fun main() {
var student = Student("Lucia", 3.95, "Fall", 2022)
//Prints: Lucia has 2 years left in college.
println("${student.name}'s letter grade is ${student.calculateLetterGrade()}.")
//Prints: Lucia's letter grade is A.
}