A simple use of joinToString() Kotlin function to get comma separated strings for SQLite

Ever since I started using Kotlin as the primary language in coding Android applications, I have been in love with it. Over the months and a great deal of observing my senior’s Kotlin code, I adopted a practice that made me utilize Kotlin at its best- Each time you have to iterate a list for gathering data, consider searching for a Kotlin function or an operator that doesn’t require you to write a for loop.

The same practice led me to use the joinToString() Kotlin method to reduce my for loop usage to create a list of comma-separated “string” values to be passed in an SQLite query.

What I had: A list of SQLite database table models (A Kotlin data class).

What I wanted for the above list: Extract a member variable from each list item and convert these members into a comma-separated “string” value to be passed to the IN SQLite operator to pass as a where clause to the SQLite delete command.

How I would have done it with Java:

How I did it with Kotlin :

… and that’s it! 9 lines of code reduced to just 1 line of code!

No for loop, no using unnecessary conditional code (to remove last appended ‘,’), and no writing line after line of code.

Kotlin joinToString() Function :

The joinToString() function is used to convert an array or a list to a string which is separated with the mentioned separator.

In the example above, I am using joinToString() to convert the list of Kotlin data classes into a comma-separated string.

Notice it -> “\’${it.nameOfStringVariable}\’” ? I am simply extracting a string member from a data class and enclosing it with single quotes. And that’s that. I set up a where clause for my string values in the SQLite command.

A comma with a space (, ) is the default separator used, if we need to use a different separator, say ‘-’, we can mention it like so:

My special thanks to https://play.kotlinlang.org for quickly letting me dry-run my code before implementing it.

For more information contact us on https://www.novumlogic.com/contactus

Categories