Kotlin / kotlinx.collections.immutable

Immutable persistent collections for Kotlin
Apache License 2.0
1.16k stars 59 forks source link

Consider adding filterTo, mapTo, etc overloads #123

Open belyaev-mikhail opened 2 years ago

belyaev-mikhail commented 2 years ago

It is very inconvenient with current API to use map(), filter() and other collection combinators, which should be the natural default style to use when working with immutable collections.

persistentList.map { it + 1 }.toPersistentList()

is extremely inefficient and

persistentList.mapTo(persistentListOf().builder()) { it + 1 }.build()

is just plain ugly.

I propose to introduce overloads for mapTo, filterTo, etc. combinators to the API. In fact, I end up defining these myself in every project I try to use ks.collections.immutable in.

Another possibility is to introduce map, filter, etc. directly, but it would suffer from the same problems that operators + and - currently have.

desgraci commented 1 year ago

what about working with List, and when u are sure that u will get into an Immutable state using the toImmutableList? honest question, not sure why an Immutable should have transforms on it? If you wanna make another Immutable you will still be creating a new object anyways.

belyaev-mikhail commented 1 year ago

persistentList.map { it + 1 }.toPersistentList() creates two intermediate objects instead of one. Also, in the particular case of filter, some persistent data structures can implement it in a persistent-friendly fashion, while filter {}.toPersistentList() obviously can't do it.

desgraci commented 1 year ago

Ah ok, got, thanks for the quick explanation and response, I knew I was missing something basic :D this is Immutable to Immutable, which makes sense for creating new ones.