Kotlin: Transform collection elements to elements of either property

Anoop M Madasseri
1 min readOct 4, 2020

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()

Option 3:

Function Reference

var serviceIds = services.map(Person::id)

--

--