Kotlin Int to String

Having converted Kotlin Int to String, we will now explore the cases when we wish to convert an Int to a String. It usually happens when we wish to append an integer into a String.

The conversion from Kotlin Int to String can happen automatically when passes inside a print statement like below:

fun main(args: Array<String>) {
     println( 1 + 2)
    println("Hello "+ 1)
    println("Hello "+ 1 + 2)
}

For the above example, the output of the code is.

Output:

3
Hello 1
Hello 12

But lets explore the cases when we wish to convert these explicitly.

Kotlin Int to String Conversion

toString() Method

The First and Foremost used method is the toString().

fun Int.toString(radix: Int): String

Let’s have a look at the declaration of the function above.

Return Type: The toString() function returns an Integer.

Radix: The Radix is the base in which we are passing the Integer.

fun main(args: Array<String>) {
	val num = 55
	val str = num.toString(10)
	println(s)
}

The output of the above code is: 55, which obtained by converting the Integer 55 to String.

Plus Operator (+)

Another way is the Plus Operator (+).

As seen above in the introduction section, when we pass an integer in the print statement, the compiler performs mathematical operation if the conditions contains no String component. But, if the String is present in the expression, it takes the expression for string and processes accordingly.

fun main(args: Array<String>) {
     println( 1 + 2)
    println( "Hello "+ 1 + 2)
}

The output of the code is self-explanatory.

Output:

3
Hello 12

That was all about Kotlin Int to String converison. Comment down below if you have any queries.

Leave a Comment

Your email address will not be published. Required fields are marked *