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 used to do this: int[] numbers = {1, 2, 3, 4, 5}; or String[] names = {"Alice", "Bob"};. Everything is simple and clear.
But in Kotlin I see several different ways and got confused. I tried to write:
val numbers = {1, 2, 3} // Compilation error
Then I read that I need to use arrayOf():
val numbers = arrayOf(1, 2, 3)
This works, but I don't understand: is this the correct way? And what should I do if I want an array of null? Or if I need an array of primitive types (IntArray, BooleanArray)?
I also saw this code:
val numbers = IntArray(5) { i No answers yet.
Log in to leave an answer
Blogs