Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effective way to append strings separated with comma [Kotlin]

Tags:

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) {
       ...        
   }
}
like image 576
JoshuaMad Avatar asked Dec 21 '17 15:12

JoshuaMad


People also ask

How do I combine strings in Kotlin?

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?

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.


2 Answers

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.

like image 189
RobCo Avatar answered Sep 17 '22 01:09

RobCo


For this example you can do this:

list
    .filter { it.isGreen }
    .joinToString()
like image 32
Daniel Amarante Avatar answered Sep 18 '22 01:09

Daniel Amarante