In Kotlin I have the following objects:
data class BugReport(
val message: String,
val bugItems: List<BugItem>,
)
And:
data class BugItem(
val title: String,
val checked: Boolean = false,
)
In a BugReport
object, how can I get only the title
property of those BugItem
s whose checked
value is equal to true
.
The idea is to get a comma separated string from the title
.
I have this code:
val checkedTitles = bugReport.bugItems.filter(BugItem::checked).joinToString()
But with this code I get the complete BugItem
objects, how can I get only the title
property?
The last parameter of joinToString
allows you to pass a function that transforms the objects to CharSequences
, so you can do
val checkedTitles = bugReport.bugItems
.filter(BugItem::checked)
.joinToString { it.title }
If you want a List<String>
containing the titles instead, you should use map
to transform the objects.
// checkedTitles is of type List<String>
val checkedTitles = bugReport.bugItems
.filter(BugItem::checked)
.map(BugItem::title)