Kotlin String to Int

In modern languages, where the entire a lot of data is fetched to and from the applications. Every I/O is majorly worked in Strings. But the problems withString is their usability. I cant find the sum of two Strings until and unless you wish to view a concatenated value.

Example:

fun main() {
	val a = "1"
	val b= "2"
	print("Sum is : "+a+b)
}

Output:

Sum is : 12

To solve such issues Kotlin had to come up with a concept in which it could allow this particular variable to be used as Integer though the Input was happening as String. This resulted in the requirement of functions which could interchange these values and help us use these values interchangeably.

Let’s see how we can use this Program to convert the String to Int before being used to sum.

fun main() {
	val a = "1"
	val b= "2"
	val sum = a.toInt()+b.toInt()
	print("Sum is "+sum);
}

The output of the above code now would return me an Integer value, hence returning the proper sum as below:

Sum is 3

The function used here is known as toInt() and lets see its use in detail.

function String.toInt() : Int

The function toInt() is called on a String object and this function returns an Integer. There could be another case when the String you are trying to convert is not an integer itself like below:

fun main() {
	val a = "a"
	val b= "2"
	val sum = a.toInt()+b.toInt()
	print("Sum is "+sum);
}

The above program would throw an NumberFormatException as it is not possible to parse “a” to a Integer.

Exception in thread “main” java.lang. NumberFormatException : For input string: “a”

at java.lang.NumberFormatException.forInputString ( NumberFormatException.java:65 )

at java.lang.Integer.parseInt ( Integer.java:580 )

at FileKt.main ( File.kt:9 )

at FileKt.main ( File.kt:-1 )

The toInt() method has another flavor to it. When you wish to pass a specific Radix as an Parameter as below definition:

function String.toInt(Radix : Int) : Int

The above method uses the same concept as that of the toInt() method but can be used for passing the Radix ( Base of the Integer to which String is parsed).

Example:

fun main() {
	val a = "1"
	val b= "2"
	val sum = a.toInt(10)+b.toInt(10)
	print("Sum is "+sum);
}

The output of the above code:

Sum is 3

Here, the if you pass an invalid Radix,we get the error as below:

fun main() {
	val a = "1"
	val b= "11"
	val sum = a.toInt(1)+b.toInt(1)
	print("Sum is "+sum);
}

The output of the above code will be as below:

Exception in thread “main” java.lang.IllegalArgumentException: radix 1 was not in valid range 2..36

at kotlin.text.CharsKt__CharJVMKt.checkRadix (CharJVM.kt:156)

at FileKt.main (File.kt:9)

at FileKt.main (File.kt:-1)

These were the functions which can be used to convert String to Int. Stay tuned for the next lecture on conversion from Int to String.

我来评几句
登录后评论

已发表评论数()

相关站点

热门文章