![]() ![]() It would be much nicer to be able to create and initialize an ArrayList directly. Obviously, this isn’t ideal as we have to convert between the two types. The toCollection() method then populates the ArrayList with all the values in the array. From that array, we can obtain an ArrayList using the toCollection() method and passing an empty ArrayList. ArrayList - Kotlin Programming Language Common JVM JS Native Version 1.8 kotlin-stdlib / llections / ArrayList ArrayList Common 1. In a single line of code, we’re able to create an array of integers using the ideal syntax. One way to reduce some of the code from above is to create an Array before converting it into an ArrayList: val list = intArrayOf(7, -4, 3).toCollection(ArrayList()) Of course, we’d love something better than this! Let’s see what Kotlin has to offer. Then, we populated that list one item at a time using the add() method. The package provides the ArrayList class, which is a mutable list that uses a dynamic resizable array as the backing storage. It contains all collection types, including Map, List, Set, etc. Kotlin Arrays Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value. Here, we’ve created an empty ArrayList of integers. The llections package is part of Kotlin’s standard library. ![]() Naturally, we can translate the Java solution almost directly: val list = ArrayList() Solutionsįortunately, Kotlin has improved quite a bit on Java’s verbosity, so I promise there’s a better way to create an ArrayList. There are some nasty workarounds, but I was hoping Kotlin would improve on the Java conventions a bit. I would prefer to be able to do something like the following: ArrayList list = new ArrayList(7, -4, 3)Īnd, for larger data sets, it would be nice to be able to spread the values over multiple lines: ArrayList list = new ArrayList( There’s just too much redundant information. In fact, I don’t even think it reads well. For reference, here’s what I don’t want to do: ArrayList list = new ArrayList()Īs you can probably imagine, this solution does not scale well. Unfortunately, there’s no clean way of initializing an ArrayList in Java, so I wondered if Kotlin had improved on that issue. As someone who came from Java, I often find myself using the ArrayList class to store data.
0 Comments
Leave a Reply. |