Idomatic way to carry object in collection chain?

This is doing my head in & I’m sure i’m missing something glaring obvious -

Is there anyway in kotlin to make the below code into a single line functional statement(i.e. returning a townLocalitiesQuery with all the values added)?

val townLocalitiesQuery = disMaxQuery()
townNameQuery
        .forEach { it -> townLocalitiesQuery.add(it) }

You didn’t specify the types so I’ll just throw out some options that may or may not work:

val townLocalitiesQuery = disMaxQuery() + townNameQuery

val townLocalitiesQuery = disMaxQuery().apply {
    addAll(townNameQuery)
} 

val townLocalitiesQuery = disMaxQuery().also { result ->
    townNameQuery.forEach { it -> result.add(it) }
} 
1 Like