astronaut4449
astronaut4449

Reputation: 11

Extension function wrapped inside class

The following example shows a class for a shopping list item, which can be multiplied to change the amount. To be able to multiply it from either side, I need an operator function for the ShoppingListItem class and the Int class. I don't like, that the extension function of the class Int is not part of the ShoppingListItem class, because it is logically connected with it. Any ideas how to wrap it inside?

data class ShoppingListItem(val name: String, val amount: Int = 1) {
    operator fun times(num: Int) = ShoppingListItem(this.name, this.amount * num)
}

operator fun Int.times(item: ShoppingListItem) = ShoppingListItem(item.name, item.amount * this)


fun main(args: Array<String>) {
    val myItem = ShoppingListItem("Apple")
    println(myItem)     // ShoppingListItem(name=Apple, amount=1)
    println(myItem * 2) // ShoppingListItem(name=Apple, amount=2)
    println(3 * myItem) // ShoppingListItem(name=Apple, amount=3)
}

Upvotes: 0

Views: 113

Answers (1)

zsmb13
zsmb13

Reputation: 89538

You can't place it inside the class - that would make it a member extension that you can only call inside the class.

The best you can do here is to place the data class and the extensions that belong to it in the same file.

Upvotes: 1

Related Questions