Search code examples
stringlistkotlinmethod-chaining

Kotlin method chaining to process strings in a list


I have a list of strings I get as a result of splitting a string. I need to remove the surrounding quotes from the strings in the list. Using method chaining how can I achieve this? I tried the below, but doesn't work.Says type interference failed.

val splitCountries: List<String> = countries.split(",").forEach{it -> it.removeSurrounding("\"")}

Solution

  • forEach doesn't return the value you generate in it, it's really just a replacement for a for loop that performs the given action. What you need here is map:

    val splitCountries: List<String> = countries.split(",").map { it.removeSurrounding("\"") }
    

    Also, a single parameter in a lambda is implicitly named it, you only have to name it explicitly if you wish to change that.