stupid question here. I want to ditch the spread o...
# announcements
l
stupid question here. I want to ditch the spread operator, but can't find a idomatic solution:
Copy code
arrayOf(
            Libraries.APPCOMPAT,
            *Libraries.KotlinExt.getAll(),
            Libraries.TIMBER
    ).forEach { // do sth. }
getAll()
returns an array but could als be another type of collection, I'm flexible here. What would be an idomatic solution?
n
curious, why do you want to ditch the spread operator?
one option might be something like
Libraries.KotlinExt.getAll() + Libraries.APPCOMPAT + Libraries.TIMBER
though that's significantly less efficient
also it would give a List rather than Array
l
it creates an temporary builder object and a new array
c
To avoid array copying, you might do something like iterate over a list of lists with
.flatten()
, use a sequence, etc.
Copy code
listOf(
    listOf(Libraries.APPCOMPAT),
    Libraries.KotlinExt.getAll(),
    listOf(Libraries.TIMBER)
).flatten().forEach { ... }
or
Copy code
sequence {
    yield(Libraries.APPCOMPAT)
    yieldAll(Libraries.KotlinExt.getAll())
    listOf(Libraries.TIMBER)
}.forEach { ... }
Though from the example you posted, it’s probably going to have more overhead to both of those than just using the spread operator. Spread is perfectly idiomatic Kotlin code, there’s no reason not to use it when it solves the problem effectively and you aren’t dealing with huge sets of data (on the order of thousands of elements)
👆 1
l
@Casey Brooks Thanks for your answer. Just of curiosity: when I use the solution of Nir I would just have 1 array. Wouldn't be this the best solution regarding performance?
c
They’re both similar. The
+
operator is still copying elements from those lists into a single bigger one at runtime.
n
The solution I gave is probably worse
because, + only gets to see two operands at a time
c
In general, though, it seems like you’re focusing on “micro-optimization” which in practice proably doesn’t make any significant impact on how your code runs. It’s better to choose the solutions that’s the most readable and maintainable, rather than using obscure patterns trying to optimize something that wasn’t really an issue in the first place
n
so you add the first two, possibly with preallocation, and then you add the result of that with the next one
Yes, indeed.
If this isn't an appropriate place to use the splat/spread operator, then what would be? This seems pretty much exactly what was in mind
👆 2
l
Well, then thank you very much guys. Really appreciated your investigation! 🙂
👍 1