https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Lukasz Kalnik

10/02/2023, 12:33 PM
How can I split a List into two at specific index in the most concise way?
I suppose
Copy code
list.withIndex().partition { it.index < selectedIndex }
Although then I end up with a
Pair<List<IndexedValue<T>>>
b

bram

10/02/2023, 12:44 PM
That will create new List objects I think, if that's acceptable, and will need to iterate through the whole list. There's the dumb and simple "sublist" you could call twice.
l

Lukasz Kalnik

10/02/2023, 12:45 PM
Yes, I suppose I won't get a nice one-liner 😉
😄 1
b

bram

10/02/2023, 12:46 PM
I love Kotlin, very very much. But the call of "Go" is strong. Dumbest, simplest, most obvious code, 0 cleverness (or elegance)
h

hho

10/02/2023, 12:51 PM
🙏 1
a

Alejandro Serrano.Mena

10/02/2023, 1:08 PM
val (before, after) = list.take(n) to list.drop(n)
👍 1
l

Lukasz Kalnik

10/02/2023, 1:14 PM
I went with
subList()
, as it doesn't create additional lists
e

Edoardo Luppi

10/02/2023, 1:14 PM
Yes, I suppose I won't get a nice one-liner
Extension function containing two calls to
subList
if it's a readonly
List<T>
l

Lukasz Kalnik

10/02/2023, 1:14 PM
👆 That's @hho’s example above
✔️ 1
e

Edoardo Luppi

10/02/2023, 1:22 PM
If you need to split in
n
parts, you can even overload the
div
operator.
Copy code
val (one, two, three, four) = list / 4
l

Lukasz Kalnik

10/02/2023, 1:29 PM
Although I just realized my list can be smaller than the split index, so I have to go with @Alejandro Serrano.Mena’s approach
take(n)
and
drop(n)
e

ephemient

10/02/2023, 3:09 PM
k

Klitos Kyriacou

10/02/2023, 5:01 PM
Although I just realized my list can be smaller than the split index, so I have to go with @Alejandro Serrano.Mena’s approach
take(n)
and
drop(n)
Instead of creating two new lists, I would stick to Henning's
subList
and just use
splitIndex.coerceAtMost(size)
.
👍 1
e

Eric-Wubbo

10/03/2023, 5:24 PM
Frankly, I also use this functionality so much that I've made my own private libraries for what Haskell has as splitAt and span(). I should really give some live examples someday because those are among the few things I would like to have extra in Kotlin (though of course it would burden the language with even more things, so there's a tradeoff...)