Kotlin for java refugees Flashcards

1
Q

Class with primary constructor

A

class Person(firstName: String) { // }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Class with properties

A

class Person(val firstName: String, val lastName: String, var isEmployed: Boolean = true)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Data classes (record)

A

data class User(val name: String, val age: Int)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Destructure data class

A

val jane = User(“Jane”, 35)

val (name, age) = jane

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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 { }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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)
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly