Skip to content

Instantly share code, notes, and snippets.

@anoopmaddasseri
Last active October 4, 2020 05:59
Show Gist options
  • Save anoopmaddasseri/fc31b446f0f2b0883896a6aca58b102d to your computer and use it in GitHub Desktop.
Save anoopmaddasseri/fc31b446f0f2b0883896a6aca58b102d to your computer and use it in GitHub Desktop.
Kotlin: Transform collection elements to elements of either property
Option 1 -
==========
inline fun <reified T, Y> MutableList<T>.listOfField(property: KMutableProperty1<T, Y?>): MutableList<Y> {
val yy = ArrayList<Y>()
this.forEach { t: T ->
yy.add(property.get(t) as Y)
}
return yy
}
Usage:
val serviceIds = services.listOfField(ServiceModel::id)
Option 2 -
==========
var serviceIds: MutableList<String> = services.map { it.id }.toMutableList();
Opition 3 [Function references] -
=================================
var serviceIds = services.map(Person::id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment