3

I see that Kotlin provides a number of interfaces for implementing collections. They are listed on this page.

I do not see any implementations of these provided by Kotlin.

I do, however, see that there are functions in the global namespace that help us create instances of these collections. For e.g. to create a mutable list of numbers, we may say:

var numbers : MutableList<Int> = mutableListOf(1, 2, 3);

To create a read-only view of the list, we may say:

val readOnlyViewOfNumbers : List<Int> = numbers;

Or, to create a read-only list of numbers, we may say:

val readOnlyListOfNumbers : List<Int> = listOf(1, 2, 3);

To create a list of n items and initialize each element with the value null, we might say:

// Sorry, I forgot the function name for this one. It
// is not nullableListOf(...)
val numbers : List<Int> = nullableListOf(n);

To create an Array, say, 5 elements with an initializer function for each element of the array, we may say:

val myArray : Array<Int> = Array(5, (i) => { /* return whatever */ };

However, if I'd like to create a List<Book> without any books in it but I'd simply like to initialize it like this (Java or C# code):

List<Book> books = new ArrayList<Book>(); // Java or
List<Book> books = new List<Book>(); // C#

How may I do that in Kotlin?

Are there publicly exposed implementations of its collection interfaces? Do they have default constructors?

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336

1 Answers1

5

Kotlin uses the implementations of Java.

So

val list = listOf<T>()

is basically

val list: List<T> = ArrayList<T>()

These functions are created for convenience

Using Java-Collections is fine too:

val list: List<Book> = ArrayList<Book>()
val mutableList: MutableList<Book> = ArrayList<Book>()
D3xter
  • 6,165
  • 1
  • 15
  • 13
  • Thank you. I understand that I can use the Java collections. I was under the impression that Kotlin standard library provided its own implementations as well. – Water Cooler v2 Sep 06 '16 at 09:36
  • 3
    They reused as much as possible of java to have a small standard-library (benefits on android -> dex-count) and to maximize interoperability. – D3xter Sep 06 '16 at 09:39