Part 07 / Topic 4 of 7
The this keyword
this refers to the object a method or constructor is currently running on. Most Kotlin code
never needs to write it -- but two situations genuinely call for it.
class ShoppingOrder(val customerName: String) {
private val items = mutableListOf<String>()
var discountPercent: Double = 0.0
// the constructor parameter is named `discountPercent`, same as the property --
// `this.discountPercent` means "the property on this object", plain
// `discountPercent` means "the parameter" inside this one function
constructor(customerName: String, discountPercent: Double) : this(customerName) {
this.discountPercent = discountPercent
}
// returning `this` lets calls be chained: order.addItem("Rice").addItem("Dal")
fun addItem(item: String): ShoppingOrder {
items.add(item)
return this
}
fun summary(): String {
val itemList = items.joinToString(", ")
return "$customerName's order: [$itemList] -- discount $discountPercent%"
}
}
val order = ShoppingOrder("Priya Deshmukh", 10.0)
.addItem("Rice")
.addItem("Dal")
.addItem("Atta")
println(order.summary())
val plainOrder = ShoppingOrder("Karan Mehta")
plainOrder.addItem("Milk")
println(plainOrder.summary())
Priya Deshmukh's order: [Rice, Dal, Atta] -- discount 10.0%
Karan Mehta's order: [Milk] -- discount 0.0%
- Disambiguation: when a parameter and a property share a name,
this.discountPercentunambiguously means the property; withoutthis, Kotlin's rule is that the closer name (the parameter) wins, which would silently do nothing useful here. - Chaining:
addItemreturnsthis-- the very same object it was called on -- so the caller can call another method straight off the result, instead of writingorder.addItem(...)three separate times.
Full program: examples/04_this_keyword.kt.
Done here? The practice set for Part 7 — including the solutions — is on the part page.