0

I am trying to create a kotlin Multiplatform library which can later convert into java and javascript using  IDEA 2019.3, kotlin 1.3

I have an array list with me and I want to convert it to a immutable list

val clean:List<String> = ArrayList<String>()

I could not see an option to convert clean to a immutable list. From here, I can see that kotlin has immutable list implementation but I could not see this in kotlin 1.3 multiplatform project.

Am I missing something obvious ? I could see a similar [old question][2] but according to this, it seems it should be available. Please help

nantitv
  • 3,539
  • 4
  • 38
  • 61

2 Answers2

1

Use Collections to converts an array list to Immutable list, Example:

Mutable Array list:

val clean:List<String> = ArrayList<String>()

Converts to Immutable list:

val immutableList = Collections.unmodifiableList(clean)
Pawan Soni
  • 860
  • 8
  • 19
1

In Kotlin, listOf(...) creates an immutable list, as stated in the documentation of the latest API.

That's why you can just write

val clean:List<String> = ArrayList<String>()
val immutableClean = listOf(clean.toImmutableList())

where immutableClean is a read only list.

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • Won't listOf( clean) produce a List>? In the end I tried something like listOf( *clean.toTypedArray()); – nantitv Jan 07 '20 at 13:15
  • @nantitv Yes, that's possible... I just payed attention to the return type being mutable or not ;-) – deHaar Jan 07 '20 at 13:24