How to initialize an array in Kotlin with specific values?
Hello! I just started learning Kotlin after Java and encountered a problem with array initialization. In Java I could simply write:
int[] numbers = {1, 2, 3, 4, 5};
But in Kotlin this doesn't work. I'm trying different options, but the compiler gives errors or I get something unexpected.
Here's what I tried:
// Option 1 (doesn't compile)
val numbers = {1, 2, 3}
// Option 2 (compiles, but it's not an array)
val numbers = arrayOf(1, 2, 3)
println(numbers) // Prints a reference, not the contents
// Option 3 (I get an array with null)
val numbers = arrayOfNulls(5)
numbers[0] = 1
numbers[1] = 2
// This is inconvenient if I need many values
I want to create an array of integers (Int, Double, String, etc.) with specific values that I set immediately at declaration. How to do this correctly?
No answers yet.
Log in to leave an answer