Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize List<T> in Kotlin?

Tags:

list

kotlin

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?

like image 213
Ali Dehghani Avatar asked Apr 27 '16 17:04

Ali Dehghani


People also ask

How do I initialize a list 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.

How do you initialize an empty list in Kotlin?

To create an empty list in kotlin, there are two ways to create an empty list in kotlin as follows: listOf() function. emptyList() function.

How do I initialize in Kotlin?

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.

How do I declare a list of strings in Kotlin?

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.


1 Answers

listOf top-level function to the rescue:

val geeks = listOf("Fowler", "Beck", "Evans") 
like image 174
Ilya Avatar answered Sep 28 '22 03:09

Ilya