Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin support string/array slices by reference like Rust and Swift?

In Rust and Swift you can create a slice of either/both arrays and strings which doesn't make a new copy of the elements but gives you a view into the existing elements using a range or iterator and implemented internally as a reference pair or reference + length.

Does Kotlin have a similar concept? It seems to have a similar concept for lists.

It's hard to Google since there is a function called "slice" which seems to copy the elements. Have I got it all wrong or is it missing?

(I'm aware I can work around it easily. I have no Java background btw.)

like image 437
hippietrail Avatar asked Sep 23 '26 23:09

hippietrail


1 Answers

I don't think so.

You can use asList to get a view of the Array as a list. Then the function you already found, subList works as usual. However, I'm not aware of an equivalent of subList for Arrays. The list returned from asList is immutable, so you cannot use it to modify the array. If you attempt to make the list mutable via toMutableList, it will just make a new copy.

fun main() {
    val alphabet = CharArray(26) { 'a' + it }
    println(alphabet.joinToString(", "))

    val listView = alphabet.asList().subList(10, 15)
    println(listView)

    for (i in alphabet.indices) alphabet[i] = alphabet[i].toUpperCase()
    println(alphabet.joinToString(", "))
    // listView is also updated
    println(listView)
}

Output:

a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
[k, l, m, n, o]
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
[K, L, M, N, O]

Using lists (or Collections) is preferred in Kotlin, and comes with much better support for generics and immutability than arrays.

If you need to mutate arrays, you probably have to manage it yourself, passing around (a reference to) the array and an IntRange of the indices you care about.

like image 107
Adam Millerchip Avatar answered Sep 26 '26 14:09

Adam Millerchip