String representation –
String representation means we can retrieve the collection content in a readable format. There are two functions that transform the collections to strings:
- joinToString()
- joinTo()
The function joinToString() builds a single String from the collection elements based on the provided arguments. And function joinTo() also builds a single string but appends the result to the given Appendable object.
When the above functions called with the default arguments, both return the result similar to calling toString() on the collection: a String of elements’ string representations separated by commas with spaces.
Kotlin program of using string representation methods –
Kotlin
fun main(args: Array<String>) { val colors = listOf("Red","Green","Blue","Orange","Yellow") println(colors) // join all elements in a single List println(colors.joinToString()) val listString = StringBuffer("Colors are: ") colors.joinTo(listString) println(listString) } |
Output:
[Red, Green, Blue, Orange, Yellow] Red, Green, Blue, Orange, Yellow Colors are: Red, Green, Blue, Orange, Yellow
Kotlin | Collection Transformation
Kotlin standard library provides different set of extension functions for collection transformations. These functions help in building new collections from existing collections based on the rules defined by the transformation.
There are different number of transformation functions:
- Mapping
- Zipping
- Association
- Flattening
- String representation