The joinToString() extension function in Kotlin creates a string from all the elements in the set, separated using the specified separator, and using the given prefix and postfix if supplied.
The syntax of Set.joinToString() extension function is:
fun <T> Set<T>.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): String
This joinToString() extension function of Set creates a string from all the elements separated using separator and using the given prefix and postfix if supplied.
Parameter | Optional/Required | Description |
---|---|---|
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.joinToString() returns value of type String
.
Using joinToString() 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 result = numbers.joinToString(separator = ", ")
println(result)
}
1, 2, 3
Using joinToString() 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 result = strings.joinToString(prefix = "[", postfix = "]")
println(result)
}
[a, b, c]
Using joinToString() 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 result = numbers.joinToString(limit = 3, truncated = "...")
println(result)
}
1, 2, 3...
In this Kotlin tutorial, we learned about joinToString() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.