develop with

How to create lists in Kotlin

Using lists and arrays in kotlin

Kotlin provides some easy ways to create list of object natively to the language. It can be done using an Array or a List object depending on the scope of where you want these container of objects to be.

The best way to create a list of objects you’ll use in a method is by using listOf. This is a built in function that given a list of objects it will return a List.

val myList = listOf(MyObject(), MyObject())

The next way to create an ordered container of objects is with the arrays. In Kotlin, arrays are defined with the Array object definition. Or an array can be created with the arrayOf function that returns the Array object.

val myArray = Array<String>()
val myArrayObj = arrayOf("myString")

Literals can be used within annotation array definitions.

For example with Swagger API definition:

@Api(tags= ["myTag1"])
class MyController {
}

Hope this helps you save time while you are developing in the future.

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.