Home > Enterprise >  How to properly import Kotlin's version of ArrayList instead of Java's?
How to properly import Kotlin's version of ArrayList instead of Java's?

Time:01-16

I just started learning Kotlin and whenever I try to import an ArrayList like this:

  fun someFunction(){
      var list = ArrayList<String>()
  }

It directs me to this class (if I ctrl click) which seems to me some kind of linking to the Java version of ArrayList:

@file:Suppress("ACTUAL_WITHOUT_EXPECT") // for building kotlin-stdlib-jvm-minimal-for-test

package kotlin.collections

@SinceKotlin("1.1") public actual typealias RandomAccess = java.util.RandomAccess


@SinceKotlin("1.1") public actual typealias ArrayList<E> = java.util.ArrayList<E>
@SinceKotlin("1.1") public actual typealias LinkedHashMap<K, V> = java.util.LinkedHashMap<K, V>
@SinceKotlin("1.1") public actual typealias HashMap<K, V> = java.util.HashMap<K, V>
@SinceKotlin("1.1") public actual typealias LinkedHashSet<E> = java.util.LinkedHashSet<E>
@SinceKotlin("1.1") public actual typealias HashSet<E> = java.util.HashSet<E>

Do I understand this right or am I making a mistake here? typealias means whenever I type ArrayList it actually links to the java.util.ArrayList, no?

Thanks in advance.

CodePudding user response:

typealias provides alternative names for existing types, type aliases do not introduce new types. They are equivalent to the corresponding underlying types

Essentially, there is only one version of ArrayList, that's java.util.ArrayList

CodePudding user response:

When you target the JVM platform, Kotlin uses Java's version of ArrayList (and many other collection classes). However, this doesn't mean that you're restricted to using only the facilities that Java provides. On the contrary, Kotlin provides many useful extension functions for its collections, irrespective of whether they are typealiases or not.

For example, you can use indices:

for (i in myList.indices)
    println("$i: $myList[i]")

You can even destructure it:

val myList = arrayListOf(16, 1, 2023)
val (d, m, y) = myList

So you should see the fact that kotlin.collections.ArrayList is a typealias of java.util.ArrayList as a mere internal implementation detail.

For a full list of capabilities, see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/

Also, if you ctrl click into ArrayList, IntelliJ is sometimes not very useful in showing you the exact definition of a typealiased class. However, you will see the exact implementation at runtime if you run under the debugger, put a breakpoint on the line where you construct the ArrayList, and then "step into".

  • Related