46

I try to do this with (same as java)

val disabledNos = intArrayOf(1, 2, 3, 4)
var integers = Arrays.asList(disabledNos)

but this doesn't give me a list. Any ideas?

Roland
  • 22,259
  • 4
  • 57
  • 84
Adolf Dsilva
  • 13,092
  • 8
  • 34
  • 45
  • 1
    The main problem why it didn't work in the first place, was, that you basically created a `List`. You need to use the [spread operator (`*`)](https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs) to get a `List`, i.e. the following would have worked too: `val integers = Arrays.asList(*disabledNos)`. A similar question, that also mentions the actual error: [Convert `Array` to `ArrayList`](https://stackoverflow.com/questions/55451118/convert-arraystring-to-arrayliststring) – Roland Apr 01 '19 at 09:29

3 Answers3

99

Kotlin support in the standard library this conversion.

You can use directly

disableNos.toList()

or if you want to make it mutable:

disableNos.toMutableList()
crgarridos
  • 8,758
  • 3
  • 49
  • 61
2

This will fix your problem :

val disabledNos = intArrayOf(1, 2, 3, 4)
var integers = Arrays.asList(*disabledNos)

Just add * to this to asList

Alok Gupta
  • 1,806
  • 22
  • 21
0

Oops that was very simple:

var integers = disabledNos.toList()
Jake Lee
  • 7,549
  • 8
  • 45
  • 86
Adolf Dsilva
  • 13,092
  • 8
  • 34
  • 45