Go with mutableListOf if that sounds like your case. mutableListOf would then have you using that new list implementation transparently, and you'd get that better behaviour for free. Likelier than not, the Kotlin team would only make that change if they figure the new implementation works better for most use cases. Now, let's say that a future version of Kotlin changes mutableListOf to return a different type of list. In practice, in the current implementation of Kotlin compiling to the JVM, calling mutableListOf will produce an ArrayList, and there's no difference in behaviour: once the list is built, everything will behave the same. When you write, instead, val a = ArrayList(), you're saying "I specifically want an ArrayList". When you write val a = mutableListOf(), you're saying "I want a mutable list, and I don't particularly care about the implementation". If you, on the other hand, want to rely on ArrayList (via arrayListOf), you probably have a concrete scenario were only this implementation is acceptable.The only difference between the two is communicating your intent. For instance, if Kotlin decides to add a more powerful backward-compatible version of an ArrayList, they could change the implementation and your code would keep working (in an improved way). As of now this happens to be an ArrayList which could change in future releases. The point of not using arrayListOf is that you want to rely on the library to choose the actual implementation. On the other hand, if you don't fully rely on type inference, you can make the variable for the ArrayList read-only as well: val l3: List = arrayListOf(2) It's definitely preferred to use read-only data structures whenever possible. One notable and important difference is that listOf gives you a read-only List whereas arrayListOf gives you a MutableList.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |