27

Assume the following Kotlin example that maps the source set src to a destination set dst:

private val src: Set<String> = setOf("hello", "world")
private val dst: Set<Int> = src.map { it.length }.toSet()

This works fine. However, IntelliJ's code inspection suggests: Call chain on collection should be converted into 'Sequence':

Call chain on collection should be converted into 'Sequence'

Applying this suggestion results in

private val dst: Set<Int> = src.asSequence().map { it.length }.toSet()

What is the benefit of this?

2 Answers2

15

In this case the suggestion is suboptimal. The correct way to rewrite this code (which also doesn't result in any IntelliJ warnings) is:

src.mapTo(hashSetOf()) { it.length }

This will avoid the creation of an intermediate list that will be subsequently converted to a set; the data will be added to the resulting set right away.

yole
  • 92,896
  • 20
  • 260
  • 197
  • 4
    Thanks, I created an issue about this: https://youtrack.jetbrains.com/issue/KT-26926. – Alexey Belkov Sep 18 '18 at 09:57
  • 2
    I haven't seen the usage of `mapTo` a lot. Is it somewhere mentioned as an idiom? Especially the shown use case if a great example – s1m0nw1 Oct 01 '18 at 12:35
14

Set.map returns a list, which you then immediately throw away after converting it to a set. The benefit of asSequence is that the sequence does the conversion, presumably without a temporary list.

Pezo
  • 1,458
  • 9
  • 15