How to initialize List in Kotlin?

后端 未结 6 1741
清酒与你
清酒与你 2021-02-03 16:36

I see Kotlin has a List collection and I was wondering about different ways to initialize one. In Java, I could write:

List geeks = Ar         


        
6条回答
  •  萌比男神i
    2021-02-03 17:04

    There is one more way to build a list in Kotlin that is as of this writing in the experimental state but hopefully should change soon.

    inline fun  buildList(builderAction: MutableList.() -> Unit): List
    

    Builds a new read-only List by populating a MutableList using the given builderAction and returning a read-only list with the same elements.

    Example:

    val list = buildList {
        testDataGenerator.fromJson("/src/test/resources/data.json").forEach {
            add(dao.insert(it))
        }
    }
    

    For further reading check the official doc.

提交回复
热议问题