Academy CHEAT SHEET
BASICS
“Hello, World” program
fun main(args: Array)¢
printin( Hello, World")
>
Declaring function
fun sumiat Int, bs Int: Int ¢
retura +b
>
Single-expression function
fun sumiar Int 6 Int) =a +
Declaring variables
val name = "Marcin” // Can't be changed
var age = 5 1 Can be changed
ages +
Variables with nullable types
var name: Sting?
val length: Int
length = name?.length 2:0
//ength, or 0 if name is null
length = name?.length 7 return
// length, or return vihen name is null
length = name? length 2: throw Error)
// length, or throw error when name is null
ll
CONTROL STRUCTURES
If as an expression
fun bigger(a: Int, b: Int) = if (a > b) a else b
For loop
val ist = HstOfA", "8
for (element in lst) (
printinfelement)
>
When expression
fun numberTypeNamete: Number) = when(s) (
0-> “Zero” // Equality check
1.4-> "Four orless* —// Range check
5, 6,7 > *Fiveto seven” // Multiple
is Byte > “Byte” 17 Type check
else-> “Some number"
:
When expression with predicates
fun signAsString In
x<0-> "Negative”
> "Zero
else -> “Positive
)
when (
CLASSES
Primary constructor
val declares a read-only property, var a mutable one
class Person(val name: String, var age: Int)
// name is read-only, age is mutable
Inheritance
‘open class Person(val name: String) (
‘open fun hello) = “Hello, | am $name"
1 Final by default so we need open
)
‘lass PolishPerson(name: String): Person(name) (
‘override fun hello = “zie dobry, jestem $name"
>
Properties with assessors
‘lass Person(var name: String, var surname: String) (
var fullName: String
get = "$name $surname"
set(value) {
val (first, rest) = valuesplit(” limit = 2)
name = first
surname = rest
’
>
Data classes
data class Person(val name: String, var age: Int)
val mike = Person("Mike’, 23)
Modifier daca adds:
1 tostring that displays all primary constructor
properties
print(mike.toString0) // Person(name=Mike, age=23)
2. equals that compares all primary constructor
properties
Person(*Mike", 23)) // True
Person(*Mike", 21))// False
3, hashCode that is based on all primary
constructor properties
val hash = mike.hashCodeQ)
Person("Mike", 23)hashCodeQ) // True
Person(*Mike", 2)hashCode() // False
4, component, component? ete. that allows
deconstruction
val (name, age) = mike
print"Sname Sage") / Mike 23
5. copy that returns copy of object with concrete
properties changed
val jake = mike.copy(ivame = "Jake")
Learn Kotlin with us: www.kt.academyAcademy CHEAT SHEET
COLLECTION LITERALS
istOf0,2,3,4) / List
‘mutabletistOf(1,2,3,4) // Mutablelist
setOf A", "B",“C°)//Set
mutablesetOfA", “B", °C") // Mutableser
arrayOfia','b,'c)//Array
mapOf. to "A", 2t0 °B") // Mop
‘mutableMapOft: to "A", 2to "B")
// MatableMap
sequenceOf(4,3,2,1) // Sequencesint>
Lito "AY // PaireInt, String>
Lista (it * 2 )//List
_generateSequence(4) {it + 2) // Sequence
COLLECTION PROCESSING
students
“filter (itpassing &8 itaverageGrade > 4.0)
/ Only passing students
sortedByDescending { itaverageGrade }
// Starting from ones with biggest grades
stake(1.0) // Take first 10
sortedWith(compareBiy({itsurname },{itmame )))
/ Sort by surname and th
generateSequence(0) (it + 1}
// Infinitive sequence of next numbers starting on O
filter {it % 2 == 0) // Keep only even
imap (it* 3} // Triple every one
take(100) // Take first 100
averaged // Count average
Most important functions for collection processing
val |= listOf.23,4)
‘iter -retums only elements matched by predicate
Ler ¢i8 % 2
‘ap - Fetus elements after transformation
mop {it* 2) // (2 4, 6,8)
‘lovvap returns elements yielded from results of trans.
UlotMap ( stOft, it + 10)¥/ (1, 17, 2.12.3, 13.4. 14)
{ole/rcluce = accumulates elements
Uold(.0) { ace, => ace +1}// 100
reduce (ace, |-> ace *i}// 24
‘ovtach/oneach = performs an action on every element
LorEach {print }// Prints 1234, returns
lonEach {print }// Prins 1234, returns (
23.4)
partition ~ splits into pair of ists
val (even, oda)
print(even) //
print(odd) // (1, 3}
‘min/max/minBy/maxBy
min // 1, possible because we can compare Int
LminBy (it) //4
max) // 4, possible because we can compare int
LmaxBy (-it)//1
first/firstBy
Lyfirst0 // 1
first (it % 2 == 0) //2 (first even number)
count = count elements matched by predicate
count (it % 2 == 09/2
sortetl/sortedy - retuns sorted collection
listOf@2,3,1,4)sortedd / 1, 2,3. 4)
lsortedBy ¢it % 23// (2.4, 1, 3)
roup8y ~ group elements on collection by key
LgroupBy (it % 2) // Mop: (T=I1, 3], O=(2, 4))
clstinet/list/netBy ~ returns only unique elements
listOf(,2,2,2).distinet9 // (1, 2)
Mutable vs immutable
collection processing functions
val list = mutableListOf(3,4,2,1)
val sortedResult = list sorted // Returns sorted
printin(sortedResult) // 1, 2,3, 4]
printinlist) // (3, 4,2, 1)
val sortResult = listsort) // Sorts mutable collection
printin(sortResult) // ko
printinlist) // (7, 2,3, 4)
lin Unit
EXTENSION FUNCTIONS
TO ANY OBJECT
ae Creed
vee oy
Sed
ice
title = "Dialog title”
‘onClick {print(*Clicked") }
)
Learn Kotlin with us: www.kt.academyeran CH EAT SH EET
FUNCTIONS
Function types
()->Unat - takes no arguments and retums nothing (Unit).
(Zat, Ent) ->Int - takes two arguments of type Int
and retums Ine.
(()->Unit)->Int - takes another function
and returns ine.
(Tat) ->()>Unit - takes argument of type Tat
and returns function.
Function literals
val ada: (Int, Int) -> Int = (1,j-> 1+)
1 Sienple larnbda expression
val printAndDouble: (Int) -> Int =
printing)
/ When single parameter, we can reference it using “it”
it*2// In lambda, last expression is returned
// Anonymous function alternative
val printAndDoubleFun: (Int) -> Int = fun In Int (
printing) // Single argument cant be referenced by it
return i * 2// Needs return lke any function
,
val i = printandDouble(10) // 10
print() // 20
Extension functions
fun Intistvend = this % 2
rint(2.isEven() // true
fun List average() = 1.0 * sum0 / size
print{istOf(, 2,3, 4)averageQ) // 25
DELEGATES
Loay - calculates value before first usage
vali by lazy { print(init"); 10 }
print() // Prints: init 10
print( // Prints: 10
ot ull - returns last setted value, or throws error
if no value has been set
observabie/vetoable - eas function every time
value changes. In vetoable function also decides
if new value should be set.
vvar name by observable("Unset") {p, old, new =>
printin("S{p.name) changed Sold -> $new")
j
name = “Marcin”
// Prints: name changed Unset -> Marcin
Map/MutableMap - finds value on map by property
name
val map = mapOf{"a" t0 10)
val a by map
print{a) // Prints: 10
VISIBILITY MODIFIERS
VARIANCE MODIFIERS
Invariance
‘lass Box <1>
=a
a
=z
no
Visible
obra ceo) | gee a | eee
Visible only in Visible in
Sea thesame class the same fle
Visible only in
Protected the same lass __Notallowed
and subclasses
Visiblein the Visible
Visible in the
Internal same module it ible nthe
classis accessible
Covariance Contravariance
class Box class Box
Wes Box