How to not expose the data structure in an object while accepting a collection of items with named parameters?

25 views Asked by At

Most of the time, we can replace a fluent interface with named parameters.

class Cart {
    fun withItems(vararg items: Item) = this
}

fun aCart(): Cart {
    TODO()
}

class Item

fun anItem(): Item {
    TODO()
}

fun main() {
    aCart().withItems(anItem(), anItem(), anItem())
}

The code snippet above can abstract away the data structure by leveraging vararg feature of the language.

I wondered if there was a way to achieve the same thing by dint of named parameters.

Can I come up with something that looks as follows?

class Cart(val withItems: Collection<Item>)

class Item

fun main() {
    Cart(
        withItems = { Item(), Item() }
    )
}

0

There are 0 answers