0

The following lambda expression operates on a class which was created outside of the lambda. I consider this clumsy. Is there a better way to this?

class Builder {
    var searchTerms = listOf<String>()
    fun build(whatever: String): Builder {
        searchTerms = searchTerms +  whatever
        return this
    }
}

fun main() {
   val b = Builder()
   val toSearch = listOf<String>("Anna", "Berta", "Carla")
   toSearch.forEach{ e-> b.build(e)}
}
Roman Funk
  • 35
  • 5
  • May be worth pointing out that builders don't tend to be used much in Kotlin, where the ability to make constructor params optional, and provide defaults, means that a single constructor can often do the job of a whole builder.  (Similarly, the ‘fluent’ style where methods return `this` each time isn't needed so much when you have functional constructs and the `with` function.) – gidds Dec 03 '19 at 00:19
  • That's true for builders that set up a bunch of parameters on one object. I'm not sure if an object that grows (like above) qualifies as the Builder pattern. If the above example were an immutable class that returns a copy with additional data, it would be just like CoroutineContext. Don't know if there's a name for this pattern. – Tenfour04 Dec 03 '19 at 14:10

1 Answers1

2

Not exactly sure what you consider clumsy about it, but if it's that you have to create a distinct line for the temporary variable, you might consider this cleaner:

fun main() {
    val toSearch = listOf<String>("Anna", "Berta", "Carla")
    val b = toSearch.fold(Builder()) { builder, e -> builder.build(e) }
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154