Is there a simpler way to extend an array?


#1

I do have an array and I want to return it with a new element. Right now I coded something like this:

  val tags = oldTagsArray   return Array<String>(tags.size + 1, {if (it < tags.size) tags[it] else NEW_STRING});

It does not seem right to me :( Is there a better, more compact way of doing this?

Thanks. Sorry for stupid question, I’m rather new to Kotlin.


#2

You can write like:

``

fun foo(old: Array<String>): Array<String> {
  val result = old.copyOf(old.size + 1)
  result[old.size] = NEW_STRING
  return result
}


#3

You can also do

``

return oldTagsArray + NEW_STRING


#4

Yep. The problem is that this expression takes an Array and returns List, and as far as I know there's no easy way to transform List back.


#5

try list.toArray()


#6

Yep, and this expression returns Array<Any>, but I do need Array<String> :-)


#7

You can write:

``

list.toArray(Array<String>(list.size, { “” }))

But I think it is not nice and if You need an Array<String> I suggest to use the first example.


#8

Thanks! That's much better. :) But it would be nice to have something like "+" here.


#9

Why are you using arrays there? Arrays are low-level data structures and should be used only where proper collections do not fit dues to performance considerations.


#10

Two reasons: - legacy. Java code had arrays there. It was rather convenient. - i tried lists, but I do need unmodifiable ones and don't know how to connect them with java List. There is another question about this somewhere around. :)


#11

It's strange that you are OK with Arrays (wich are inherently mutable), but reauire unmodifiable lists...


#12

I needed some method that returns several strings. Well, it's an array of tags that are required for a module to run. It is a constant list for a module. I only request them and then iterate through them.

So I’ve decided to go with the easiest way syntactically. Of course there were many possible solutions but that was the first that came into my mind. It was OK then.

And not it allowed me to find out about useful Kotlin annotations and several other things. I’ll rethink this solution based on these questions.