9

I can't figure out a way to add values to an array in Kotlin .

I want to get values from user and add them to the array.

val arr = arrayOf<Int>()

or

var arr = intArrayOf()

In Java I would do something like this:

Scanner ob = new Scanner(System.in);
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
   arr[i]=ob.nextInt();
}

How can I do the same in Kotlin?

mjuarez
  • 16,372
  • 11
  • 56
  • 73
Aman gautam
  • 822
  • 2
  • 9
  • 20
  • 1
    Possible duplicate of [Difference between List and Array types in Kotlin](https://stackoverflow.com/questions/36262305/difference-between-list-and-array-types-in-kotlin) – Michael Easter Jul 15 '17 at 20:41
  • @MichaelEaster I'd like to say there is no duplications. – holi-java Jul 15 '17 at 21:08
  • See also [Reading console input in Kotlin](https://stackoverflow.com/questions/41283393/reading-console-input-in-kotlin/41283570#41283570) with ready-to-use functions for reading arrays – Vadzim May 25 '19 at 12:58

2 Answers2

10

You need to escape the static field in of System class with backtick (`), since in is a keyword in Kotlin. for example:

val ob = Scanner(System.`in`)

You can create a fixed size int[] array without initializing it immediately in Kotlin, then the default value of the elements in array are 0. for example:

val arr = IntArray(5) // create IntArray via constructor

There is a bit different for using for-loop in Kotlin, for example:

for(i in 0 until arr.size){
    arr[i] = ob.nextInt();
}

OR initializing an int[] array during creation, for example:

val arr = IntArray(5){ ob.nextInt() }
holi-java
  • 29,655
  • 7
  • 72
  • 83
4

Arrays have fixed sizes. When creating an array, you will have to declare it's size during initialization.

val arr: IntArray = intArrayOf(1, 2, 3)

or

val arr = arrayOf(1, 2, 3)

or

val arr = Array (3){it}

If you want to create a collection that you can dynamically add values to, then you can create a mutable list.

val list = mutableListOf<Int>()
list.add(1)
list.add(2)
list.add(3)
A. Shevchuk
  • 2,109
  • 14
  • 23
Alf Moh
  • 7,159
  • 5
  • 41
  • 50