I was wondering if there is an effective way of separating different strings with comma as the separator?
In Java8
there was StringUtils.join(java.lang.Iterable,char)
.
For Kotlin
I only found joinToString
, which converts from array/list to string. As I understand, joinToString
converts whole list/array. What if I want to convert a few items from array to comma separated string not all of them? How would one do that? Is there something short and elegant from Kotlin
(obviously, I can make my own function for this, but I was just wondering).
list.forEachIndexed { index, item ->
if (item.isGreen) {
...
}
}
Using + Operator The + operator is one of the widely used approaches to concatenate two strings in Kotlin. Alternatively, you can use the plus() function to concatenate one string at the end of another string.
What Is String Interpolation in Kotlin? A string interpolation or interpolation expression is a piece of code that is evaluated and returns a string as a result. In Kotlin, string interpolation allows us to concatenate constant strings efficiently and variables to create another string.
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.
For this example you can do this:
list
.filter { it.isGreen }
.joinToString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With