I see Kotlin has a List<out E>
collection and I was wondering about different ways to initialize one. In Java, I could write:
List<String> geeks = Arrays.asList("Fowler", "Beck", "Evans");
How can I achieve the same in Kotlin?
Android Dependency Injection using Dagger with KotlinList<T> denotes a List collection of generic data type. By <T>, we understand that the List does not have any specific data type. Let's check how we can initialize such a collection in Kotlin. List<T> can be of two types: immutable and mutable.
To create an empty list in kotlin, there are two ways to create an empty list in kotlin as follows: listOf() function. emptyList() function.
To initialize a String variable in Kotlin, we may assign the String literal to the variable without specifying explicit type, or we may declare a variable of type String and assign a String literal later.
To define a list of Strings in Kotlin, call listOf() function and pass all the Strings as arguments to it. listOf() function returns a read-only List. Since, we are passing strings for elements parameter, listOf() function returns a List<String> object.
listOf
top-level function to the rescue:
val geeks = listOf("Fowler", "Beck", "Evans")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With