Effective way to append strings separated with comma [Kotlin]

Answer #1 100 %
val greenString = list.filter(ItemClass::isGreen).joinToString()

Here, ItemClass is the type of your item which defines the isGreen function or property. ItemClass::isGreen is a reference to this method/property.

You could also use a lambda for the same effect (see other answer).


Edit: You can specify how the object should be represented as a String in the joinToString function with the transform argument.
Because this is the last parameter it can be given outside of the regular parentheses:

list.filter(ItemClass::isGreen).joinToString() { it.content.text }

You could even leave off the parentheses all together now but they may be used for other arguments.
You can not use the reference style (::) here because it is a complex expression and not a direct reference to a specific method or property.



Answer #2 94.7 %

For this example you can do this:

list
    .filter { it.isGreen }
    .joinToString()
Tags: kotlin

You’ll also like:


© 2023 CodeForDev.com -