Why does IntelliJ suggest to convert a call chain into a Sequence?

  • A+
Category:Languages

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':

Why does IntelliJ suggest to convert a call chain into a Sequence?

Applying this suggestion results in

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

What is the benefit of this?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: