Kotlin List joinTo()
Syntax & Examples


Syntax of List.joinTo()

The syntax of List.joinTo() extension function is:

fun <T, A : Appendable> Iterable<T>.joinTo( buffer: A, separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null ): A

This joinTo() extension function of List appends the string from all the elements separated using separator and using the given prefix and postfix if supplied.



✐ Examples

1 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry".
  • We create a StringBuilder named buffer to store the joined string.
  • We use the joinTo function to join elements of list with a separator ", ", a prefix "[", and a postfix "]".
  • The result is stored in buffer.
  • Finally, we print the joined string from buffer to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry")
    val buffer = StringBuilder()
    val result = list.joinTo(buffer, separator = ", ", prefix = "[", postfix = "]")
    println(result)
}

Output

[apple, banana, cherry]

2 Example

In this example,

  • We create a list of integers named list containing elements 10, 20, 30.
  • We create a StringBuilder named buffer to store the joined string.
  • We use the joinTo function to join elements of list with a separator "-", a prefix "Numbers:", and a postfix "!".
  • The result is stored in buffer.
  • Finally, we print the joined string from buffer to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(10, 20, 30)
    val buffer = StringBuilder()
    val result = list.joinTo(buffer, separator = "-", prefix = "Numbers:", postfix = "!")
    println(result)
}

Output

Numbers:10-20-30!

3 Example

In this example,

  • We create a list of strings named list containing elements "red", "blue", "green".
  • We create a StringBuilder named buffer to store the joined string.
  • We use the joinTo function to join elements of list without specifying a separator, prefix, or postfix.
  • The result is stored in buffer.
  • Finally, we print the joined string from buffer to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("red", "blue", "green")
    val buffer = StringBuilder()
    val result = list.joinTo(buffer)
    println(result)
}

Output

red, blue, green

Summary

In this Kotlin tutorial, we learned about joinTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.