Pierre Henry
Pierre Henry

Reputation: 17487

Kotlin: idiomatic way to map a list of objects to a list of values from one field?

I map a list of objects to a list of the value of one of the fields of the objects.

In this case, the variable languages is a List<Language> where the class Language has a field code that is of type String:

val languageCodes:List<String> = languages.map { language -> language.code }

Is there a more idiomatic and/or concise way to do this (except to omit the type of the list, which I left in this example for the sake of clarity)?

Upvotes: 2

Views: 1631

Answers (2)

Todd
Todd

Reputation: 31710

You more or less have it. To make it a bit clearer, you could eliminate language in favor of it, the default name of a single argument to a lambda:

val languageCodes = languages.map { it.code }

But what you have would work just as well, and is probably about as clear (this is subjective). You'll notice I named my val "languageCodes", as your reuse of languages wouldn't compile.

Upvotes: 5

Pierre Henry
Pierre Henry

Reputation: 17487

I found about the it keyword that refers to an implicit single parameter of a lambda:

val languageCodes:List<String> = languages.map { it.code }

Pretty neat!

Quoting the official doc:

It's very common that a lambda expression has only one parameter. If the compiler can figure the signature out itself, it is allowed not to declare the only parameter and omit ->. The parameter will be implicitly declared under the name it.

Upvotes: 0

Related Questions