Careeroza
apply
Configure and Return the Object
apply returns the object itself, so it is perfect for setting up a new object: "create this, and apply these settings".
Example
class Notification {
var title = ""
var body = ""
var priority = "normal"
var channel = "general"
override fun toString() = "[$channel/$priority] $title - $body"
}
fun main() {
val n = Notification().apply {
title = "Flash Sale"
body = "Up to 70% off on electronics"
priority = "high"
}
println(n)
val list = mutableListOf<String>().apply {
add("Wi-Fi")
add("AC")
addAll(listOf("Breakfast", "Parking"))
}
println(list)
}Output
[general/high] Flash Sale - Up to 70% off on electronics [Wi-Fi, AC, Breakfast, Parking]