Careeroza
Object Expressions
Anonymous Objects
An object expression creates a one-off object of an anonymous class - Kotlin's version of Java anonymous inner classes. Use it when an interface has more than one function (so a lambda is not enough).
Example
interface DownloadListener {
fun onProgress(percent: Int)
fun onComplete(file: String)
}
fun download(file: String, listener: DownloadListener) {
for (p in listOf(25, 50, 100)) listener.onProgress(p)
listener.onComplete(file)
}
fun main() {
var updates = 0
download("report.pdf", object : DownloadListener {
override fun onProgress(percent: Int) {
updates++ // can use outer variables
println("Progress: $percent%")
}
override fun onComplete(file: String) = println("Saved $file after $updates updates")
})
}Output
Progress: 25% Progress: 50% Progress: 100% Saved report.pdf after 3 updates
Ad-hoc Objects
Example
Inside a function you can also create a quick object with properties.
fun main() {
val point = object {
val x = 10
val y = 20
fun sum() = x + y
}
println("x=${point.x}, y=${point.y}, sum=${point.sum()}")
}Output
x=10, y=20, sum=30