![]() ![]() From that array, we can obtain an ArrayList using the toCollection() method and passing an empty ArrayList. 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. Here, we’ve created an empty ArrayList of integers. 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. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |