Concatenate integers to a string in Kotlin
This article explores different ways to concatenate integers to a string in Kotlin.
1. Using String templates
An elegant and concise solution to concatenate multiple integers to a string is using String templates in Kotlin. A template expression starts with a dollar sign ($) and consists of a name or an expression:
|
1 2 3 4 5 6 7 8 |
fun main() { val a = 5 val b = 2 val c = 4 val s = "$a$b$c" println(s) // 524 } |
2. Using String concat (+)
Another option is to use the String concat operator + to concatenate integers to a string. This is demonstrated below using an empty string literal (or valueOf() function):
|
1 2 3 4 5 6 7 8 |
fun main() { val a = 5 val b = 2 val c = 4 val s = "" + a + b + c // a.toString() + b + c println(s) // 524 } |
3. Using joinToString() function
To concatenate multiple integers to a string, it is useful to create a utility function that accepts a vararg. The joinToString() function can join all vararg elements using a separator and transform function (to convert each integer to a string).
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concatenate(vararg digits: Int): String { return digits.joinToString(separator = "", transform = Int::toString) } fun main() { val a = 5 val b = 2 val c = 4 val s = concatenate(a, b, c) println(s) // 524 } |
4. Using String.format() function
Finally, we can use the String.format() function to get the formatted string from the specified integer arguments with the %s format specifier.
|
1 2 3 4 5 6 7 8 |
fun main() { val a = 5 val b = 2 val c = 4 val s = String.format("%s%s%s", a, b, c) println(s) // 524 } |
That’s all about concatenating integers to a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)