Last active
October 4, 2020 05:59
-
-
Save anoopmaddasseri/fc31b446f0f2b0883896a6aca58b102d to your computer and use it in GitHub Desktop.
Kotlin: Transform collection elements to elements of either property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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