Copilot Kotlin: Convert a list of numbers to string
Video: Copilot Kotlin: Convert a list of numbers to string by Taught by Celeste AI - AI Coding Coach
Watch full page →Copilot Kotlin: Convert a list of numbers to string
In Kotlin, converting a list of numbers into a single string is a common task that can be done efficiently using built-in functions. This example demonstrates how to transform a list of integers into a formatted string, making it easy to display or log the values.
Code
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// Convert the list of numbers to a comma-separated string
val result = numbers.joinToString(separator = ", ")
println(result) // Output: 1, 2, 3, 4, 5
}
Key Points
- The Kotlin function
joinToString()converts collections into formatted strings easily. - You can specify a separator such as a comma, space, or any string between elements.
- This method works with any collection of elements, not just numbers.
- Using
joinToString()keeps code concise and readable compared to manual loops.