Is there a simpler way to extend an array?


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.


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


You can also do


return oldTagsArray + NEW_STRING


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.


try list.toArray()


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


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.


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


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.


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. :)


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


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.