127

I am working on a console application in Kotlin where I accept multiple arguments in main() function

fun main(args: Array<String>) { // validation & String to Integer conversion } 

I want to check whether the String is a valid integer and convert the same or else I have to throw some exception.

How can I resolve this?

8
  • 1
    Use String.toInt(), wrap it in try-catch and handle the NumberFormatException. Commented May 28, 2018 at 16:24
  • Thanks for the response but I see there is no String.toInt() available. Commented May 28, 2018 at 16:27
  • 3
    It's not a static method, you have to call toInt() on your String instances. For example args[0].toInt(). Commented May 28, 2018 at 16:30
  • Thanks, that worked. Still working with the try-catch block. Commented May 28, 2018 at 16:34
  • 6
    You can also use toIntOrNull to get a Int? result, that way you don't have to use try-catch. Commented May 28, 2018 at 16:35

12 Answers 12

141

You could call toInt() on your String instances:

fun main(args: Array<String>) { for (str in args) { try { val parsedInt = str.toInt() println("The parsed int is $parsedInt") } catch (nfe: NumberFormatException) { // not a valid int } } } 

Or toIntOrNull() as an alternative:

for (str in args) { val parsedInt = str.toIntOrNull() if (parsedInt != null) { println("The parsed int is $parsedInt") } else { // not a valid int } } 

If you don't care about the invalid values, then you could combine toIntOrNull() with the safe call operator and a scope function, for example:

for (str in args) { str.toIntOrNull()?.let { println("The parsed int is $it") } } 
Sign up to request clarification or add additional context in comments.

Comments

40

Actually, there are several ways:

Given:

// aString is the string that we want to convert to number // defaultValue is the backup value (integer) we'll have in case of conversion failed var aString: String = "aString" var defaultValue : Int = defaultValue 

Then we have:

Operation Successful operation Unsuccessful Operation
aString.toInt() Numeric value NumberFormatException
aString.toIntOrNull() Numeric value null
aString.toIntOrNull() ?: defaultValue Numeric value defaultValue

If aString is a valid integer, then we will get is numeric value, else, based on the function used, see a result in column Unsuccessful Operation.

3 Comments

A table is not easy to understand. Please, add column titles. What is true and false?
Hi CoolMind, the first row is column title, it answers the question (numberString is a valid number) is true or false
Sorry, I again understood the table not so easily, so edited the answer.
20
val i = "42".toIntOrNull() 

Keep in mind that the result is nullable as the name suggests.

Comments

8

If you actually have a String, call toInt() on it:

val myInt = myString.toInt() 

Are you actually sure it's a String, though? If you're iterating over a single String, you don't get instances of String of length 1 (as you might expect if you're used to another language, ie, Python), but instances of Char, in which case you want to use digitToInt() instead:

val myInt = myChar.digitToInt() 

2 Comments

Why the toString() call? The asker already has a string to work with.
While this piece of code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive feedback/upvotes from users, when the code is explained.
7

As suggested above, use toIntOrNull().

Parses the string as an [Int] number and returns the result or null if the string is not a valid representation of a number.

val a = "11".toIntOrNull() // 11 val b = "-11".toIntOrNull() // -11 val c = "11.7".toIntOrNull() // null val d = "11.0".toIntOrNull() // null val e = "abc".toIntOrNull() // null val f = null?.toIntOrNull() // null 

Comments

5

In Kotlin:

Simply do that

val abc = try {stringNumber.toInt()}catch (e:Exception){0} 

In catch block you can set default value for any case string is not converted to "Int".

Comments

4

I use this util function:

fun safeInt(text: String, fallback: Int): Int { return text.toIntOrNull() ?: fallback } 

1 Comment

2

i would go with something like this.

import java.util.* fun String?.asOptionalInt() = Optional.ofNullable(this).map { it.toIntOrNull() } fun main(args: Array<String>) { val intArgs = args.map { it.asOptionalInt().orElseThrow { IllegalArgumentException("cannot parse to int $it") } } println(intArgs) } 

this is quite a nice way to do this, without introducing unsafe nullable values.

2 Comments

Thanks for the response. I am a newbie in Kotlin, can you please add some comments to explain the code provided? that might also help others
This is just a longer slower way to write it.toIntOrNull() ?: throw IllegalArgumentException("cannot parse to int $it").
2

toInt()

You can call toInt() on a String to turn it into an Integer.

val number_int = str.toInt() 

If it cannot be converted, it will throw a NumberFormatException error.

You could put it in a try-catch block:

try { val strVal = "IamNotanInteger" val intVal = strVal.toInt() println(intVal) } catch (e: NumberFormatException) { println("This String is not convertible.") } 

toIntOrNull()

toIntOrNull() will also convert a String into an Integer, but it will return null instead of throwing an error.

fun main() { val strVal = "246b" val intVal = strVal.toIntOrNull() println(intVal) // null } 

Integer.parseInt()

Here’s how to use the parseInt() method to convert Kotlin String to Int.

fun main() { val strVal = "246" val intVal = Integer.parseInt(strVal) println(intVal) // 246 } 

Non-Decimal System

You can pass a radix into the toInt() and toIntOrNull() methods:

fun main() { val base16String = "3F" val base16Int = base16String.toInt(16) // String Interpolation println("$base16Int") // 63 (If I did the maths correct...) } 

Useful Links

Comments

1

add (?) before fun toInt()

val number_int = str?.toInt()

Comments

1

You can Direct Change by using readLine()!!.toInt()

Example:

fun main(){ print("Enter the radius = ") var r1 = readLine()!!.toInt() var area = (3.14*r1*r1) println("Area is $area") } 

Comments

0
fun getIntValueFromString(value : String): Int { var returnValue = "" value.forEach { val item = it.toString().toIntOrNull() if(item is Int){ returnValue += item.toString() } } return returnValue.toInt() } 

1 Comment

Please don't post only code as an answer, but include an explanation what the code does and how it solves the problem of the question. Answers with an explanation are generally of higher quality, and more likely to attract upvotes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.