How to initialize an array in Kotlin?

Asked

Viewed 3,586 times

6

I need to initialize an array in Kotlin more do not know how to do, in Java I did so:

int numeros[] = new int[] {0,1,3,4,5,6,7,8,9};
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

6

The most common form is this:

val numeros : IntArray = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

But it can also be:

val numeros = Array(10, { i -> i })

Here:

import java.util.*
 
fun main(args: Array<String>) {
    val numeros: IntArray = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    val numeros2 = Array(10, { i -> i })
    println(Arrays.toString(numeros))
    println(Arrays.toString(numeros2))
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I was just going to talk about IntArray :] - ps: Bytearray and Shortarray also :P, but already fixed hehehe. PS: the second one sounds more interesting to me because I can after Arrow insert the values dynamically according to the interest. + 1

  • codingground with error: timeout: failed to run command ‘kotlinc’: Permission denied, must be their bug. ps: I’m not logged in to them

  • with you in Java doing the dynamic array, just like you did?

  • In the hand you can, and you can create a function for this :)

  • @Guilhermenascimento why I put in different places, there’s always one failing :)

  • @Matheushenrique depends on what is dynamic for you, as I explained above, the interesting second way with Arrow -> is to pass the value you want generating as needed, since the i there after the -> it’s just an example, it could be anything :)

Show 1 more comment

1

Since the question is not specifically for Int array, although it is included in the example, we create object arrays in Kotlin:

val arrayOfStrings = arrayOf("A", "B", "C")
val arrayOfFoo = arrayOf(Foo(1), Foo(2), Foo(3))

and so on.

The signature of the arrayOf method is:

inline fun <reified T> arrayOf(vararg elements: T): Array<T>

With this function you can create arrays of any type.


However

For primitive type arrays(int, double, short, ...), it is recommended that you use special functions, which follow a similar signature:

val arrayOfInts = intArrayOf(1, 2, 3)
val arrayOfDoubles = doubleArrayOf(1.0, 1.1, 1.2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.