Search code examples
lambdakotlindata-class

Function to lambda expression


I have a data class and I need to initialize some List<String>. I need to get the values of a JsonArray (I'm using Gson).

I made this function:

private fun arrayToList(data: JsonArray, key: String): List<String> {
    val list = mutableListOf<String>()

    data.forEach { a ->
        list.add(a[key].asString)
    }

    return list
}

How can I convert to work as a lambda expression?

Thanks.


Solution

  • I think you're looking for the map operation:

    data.map { a -> a[key].asString }
    

    Or you can use the default parameter name it:

    data.map { it[key].asString }