Kotlin program to convert one list to string

Introduction :

Converting one list to string in Kotlin is easy. Kotlin provides one method to do that easily. It is called joinToString. In this post, I will show you how we can convert one list to string in Kotlin using joinToString with examples.

Definition :

This method is defined as below :

fun  Iterable.joinToString(
    separator: CharSequence = ", ",
    prefix: CharSequence = "",
    postfix: CharSequence = "",
    limit: Int = -1,
    truncated: CharSequence = "...",
    transform: ((T) -> CharSequence)? = null
): String

Here, separator : This is the element separator used to separate all elements. prefix : This is prefix of the final string postfix : This is the postfix of the final string limit : Number of first elements to append in the final string truncated : Truncated string transform : Transform operation

Example of joinToString :

Let’s consider the below example :

fun main() {
    val givenList = listOf(1, 2, 3, 4, 5)

    println(givenList.joinToString(":", "{", "}", 4, "...etc") { (it * 2).toString() })

The first print method converted the list to string using joinToString and printed it. The second print method converted it using all parameters. It will print the below output :

1, 2, 3, 4, 5

Kotlin list to string

Similar tutorials :

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️