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 ): AThis 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
listcontaining elements"apple", "banana", "cherry". - We create a
StringBuildernamedbufferto store the joined string. - We use the
joinTofunction to join elements oflistwith a separator", ", a prefix"[", and a postfix"]". - The result is stored in
buffer. - Finally, we print the joined string from
bufferto 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
listcontaining elements10, 20, 30. - We create a
StringBuildernamedbufferto store the joined string. - We use the
joinTofunction to join elements oflistwith a separator"-", a prefix"Numbers:", and a postfix"!". - The result is stored in
buffer. - Finally, we print the joined string from
bufferto 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
listcontaining elements"red", "blue", "green". - We create a
StringBuildernamedbufferto store the joined string. - We use the
joinTofunction to join elements oflistwithout specifying a separator, prefix, or postfix. - The result is stored in
buffer. - Finally, we print the joined string from
bufferto 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.