0

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() }
    )
}

ibrahim koz
  • 537
  • 4
  • 15
  • Not with the curly braces like that. You can always write `withItems = listOf(Item(), Item())` – Louis Wasserman Aug 29 '22 at 17:22
  • Dude, this was what I had emphasized in the question. I don't want to expose the data structure to store those elements. By doing this, you expose that you use a list data structure to store those items which leads to breaking the encapsulation. – ibrahim koz Aug 29 '22 at 21:23
  • That is the best you can do in Kotlin. Sorry if you were hoping for another answer. – Louis Wasserman Aug 29 '22 at 21:34

0 Answers0