Kotlin for java refugees Flashcards
1
Q
Class with primary constructor
A
class Person(firstName: String) { /…/ }
2
Q
Class with properties
A
class Person(val firstName: String, val lastName: String, var isEmployed: Boolean = true)
3
Q
Data classes (record)
A
data class User(val name: String, val age: Int)
4
Q
Alter data class
A
// Copy the data with the copy function val jack = User(name = "Jack", age = 1) val olderJack = jack.copy(age = 2)
5
Q
Destructure data class
A
val jane = User(“Jane”, 35)
val (name, age) = jane
6
Q
Companion object
A
class MyClass { companion object Factory { fun create(): MyClass = MyClass() }
// The name of the companion object can be omitted companion object { } }
7
Q
Extension functions
A
// prefix function name with a receiver type, which refers to the type being extended fun MutableList.swap(index1: Int, index2: Int) { val tmp = this[index1] // 'this' corresponds to the list this[index1] = this[index2] this[index2] = tmp }
8
Q
Scope function - let
A
// Without let : val alice = Person("Alice", 20, "Amsterdam") println(alice) alice.moveTo("London") alice.incrementAge() println(alice)
// With let Person("Alice", 20, "Amsterdam").let { println(it) it.moveTo("London") it.incrementAge() println(it) }
9
Q
Higher-Odrer function
A
fun Collection.fold( initial: R, combine: (acc: R, nextElement: T) -> R ): R { var accumulator: R = initial for (element: T in this) { accumulator = combine(accumulator, element) } return accumulator }