Class with primary constructor
class Person(firstName: String) { /…/ }
Class with properties
class Person(val firstName: String, val lastName: String, var isEmployed: Boolean = true)
Data classes (record)
data class User(val name: String, val age: Int)
Alter data class
// Copy the data with the copy function val jack = User(name = "Jack", age = 1) val olderJack = jack.copy(age = 2)
Destructure data class
val jane = User(“Jane”, 35)
val (name, age) = jane
Companion object
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
// The name of the companion object can be omitted
companion object { }
}Extension functions
// 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
}Scope function - let
// 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)
}Higher-Odrer function
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
}