添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

It's not a static method, you have to call toInt() on your String instances. For example args[0].toInt(). – earthw0rmjim May 28, 2018 at 16:30 You can also use toIntOrNull to get a Int? result, that way you don't have to use try-catch. – zsmb13 May 28, 2018 at 16:35 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")

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:

Hi CoolMind, the first row is column title, it answers the question (numberString is a valid number) is true or false – Hoa Nguyen Aug 30, 2019 at 14:05

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
                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.
– Amit Verma
                Feb 28, 2021 at 11:56
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.

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 – Sai Sarath C P May 28, 2018 at 17:48 This is just a longer slower way to write it.toIntOrNull() ?: throw IllegalArgumentException("cannot parse to int $it"). – Alexey Romanov May 28, 2018 at 19:58 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. – Mark Rotteveel Oct 23, 2019 at 6:37

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.