The joinTo() extension function in Kotlin appends the string representation of all the elements in the set, separated using the specified separator, and using the given prefix and postfix if supplied.
The syntax of Set.joinTo() extension function is:
fun <T, A : Appendable> Set<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 Set appends the string from all the elements separated using separator and using the given prefix and postfix if supplied.
Parameter | Optional/Required | Description |
---|---|---|
buffer | required | The Appendable to which the elements will be appended. |
separator | optional | The separator used between elements. Default is ", ". |
prefix | optional | The prefix added before the first element. Default is an empty string. |
postfix | optional | The postfix added after the last element. Default is an empty string. |
limit | optional | The maximum number of elements to be appended. Default is -1, which means no limit. |
truncated | optional | The string that will be appended if the limit is reached. Default is "...". |
transform | optional | A function that transforms an element into a CharSequence which will be appended. Default is null. |
Set.joinTo() returns value of type A
.
Using joinTo() to join elements in a set of integers into a string with a comma separator.
For example,
fun main() {
val numbers = setOf(1, 2, 3)
val buffer = StringBuilder()
numbers.joinTo(buffer, separator = ", ")
println(buffer.toString())
}
1, 2, 3
Using joinTo() to join elements in a set of strings into a string with a prefix and postfix.
For example,
fun main() {
val strings = setOf("a", "b", "c")
val buffer = StringBuilder()
strings.joinTo(buffer, prefix = "[", postfix = "]")
println(buffer.toString())
}
[a, b, c]
Using joinTo() to join elements in a set of integers into a string with a limit and truncated string.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val buffer = StringBuilder()
numbers.joinTo(buffer, limit = 3, truncated = "...")
println(buffer.toString())
}
1, 2, 3...
In this Kotlin tutorial, we learned about joinTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.