what's the idiomatic way to create a Set (immutabl...
# android
t
what's the idiomatic way to create a Set (immutable) from a collection mapping operation? The following works, but seems kind of round about:
Copy code
val beginEdges: Set<Duration>
    get() = emptySet<Duration>() + spans.asSequence().map({ span -> span.begin })
setOf() takes varargs, but I'm not aware of a pythonesque ability to ** an iterable argument to varargs...
e
Copy code
spans.mapTo(mutableSetOf()) { span -> span.begin() }
can be used as a
Set
, as long as nobody casts it back to a
MutableSet
if you're concerned about that,
Copy code
buildSet { spans.mapTo(this) { span -> span.begin() } }
will create a Set that will throw on mutation
it is possible to
Copy code
setOf(*spans.map { span -> span.begin }.toTypedArray())
but that requires going through an Array twice (due to varargs copying)
I assume your real usage is more complex, because in your example you could simply have used the
fun <T> Sequence<T>.toSet(): Set<T>
extension…
🙏 1
âž• 1