How to initialize an array in Kotlin?

6

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

int numeros[] = new int[] {0,1,3,4,5,6,7,8,9};
    
asked by anonymous 19.04.2018 / 21:58

2 answers

5

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))
}

See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .

    
19.04.2018 / 22:01
1

As the question is not specifically for Int array, although it is included in the example, so 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 arrays of primitive types (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)
    
25.04.2018 / 17:47