我看到Kotlin有一个List<out E>
集合,但我不知道如何初始化它。在Java中,我可以这样写:如何在Kotlin中初始化列表<T>?
List<String> geeks = Arrays.asList("Fowler", "Beck", "Evans");
如何在Kotlin中实现相同?
我看到Kotlin有一个List<out E>
集合,但我不知道如何初始化它。在Java中,我可以这样写:如何在Kotlin中初始化列表<T>?
List<String> geeks = Arrays.asList("Fowler", "Beck", "Evans");
如何在Kotlin中实现相同?
listOf
顶级函数救援:
val geeks = listOf("Fowler", "Beck", "Evans")
不带任何参数调用[listOf](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/list-of.html)会让你获得一个空的列表,或者只需调用[emptyList](https: //kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/empty-list.html)以使其更具可读性。 – frogcoder
还有[arrayListOf](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/array-list-of.html) –
@GregT你是真正的MVP :)谢谢! – cesarferreira
只是为了增加更多的信息,科特林提供不可变的List
和MutableList
可以与listOf
和mutableListOf
进行初始化。如果您对Kotlin提供有关Collections的更多兴趣,可以访问官方参考文档Collections。
With ['listOf'](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/list-of.html)? – Michael