Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly map to set in Kotlin

Tags:

After I map through one Set, I have to explicitly cast it back to Set. For example:

fun getNewSet(oldSet: Set<String>): Set<String> { return oldSet         .map{ getNewStringFromOld(it) }         .toSet() } 

What is the proper way to map through the set without explicitly casting it back to Set?

like image 908
arslancharyev31 Avatar asked Mar 20 '17 20:03

arslancharyev31


People also ask

How do you set a value on map in Kotlin?

To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map.

What is ArrayMap in Kotlin?

kotlin.Any. ↳ android.util.ArrayMap. ArrayMap is a generic key->value mapping data structure that is designed to be more memory efficient than a traditional java.

What is mapOf in Kotlin?

The kotlin mapOf is defined as the function and it is one of the util collections and it is denoted under the interface it accepts keys and values for the user-defined types the key based mapped values are processing at the capabilities for to store and retrieving the values with the help of specific keys it also been ...


1 Answers

Looking at the library code, the only other way to do this would be to call mapTo which takes a destination collection:

oldSet.mapTo(HashSet<String>()) { getNewStringFromOld(id) } 

I'm not sure the default is wrong. The problem is that map might be used in a way that results in a list of non-unique values. If there was a special version of Set.map() that returned a set, you couldn't use map in that way - any non-unique value would replace the value in the result. I could certainly see the case being made that map should always result in a collection that is the same size as the source collection, and if map created a Set, this wouldn't always be the case.

If you do this often, perhaps just create your own extension function:

public inline fun <T, R> Iterable<T>.mapToSet(transform: (T) -> R): Set<R> {   return mapTo(HashSet<R>(), transform) } 
like image 118
Jon Nichols Avatar answered Sep 20 '22 22:09

Jon Nichols