Home > Software engineering >  Is it valid to use readLine()!! without adding toInt() if the input is an Int?
Is it valid to use readLine()!! without adding toInt() if the input is an Int?

Time:10-07

Sorry for this dumb question:

It says readLine()!! reads line as a string, but if I enter an integer without adding .toInt(), it runs fine?:

Sample input: 55

fun main() {

   println("Enter any number here: ")
   val a = readLine()!!
   print(a)

}

//prints 55

I am a bit confused, because it prints 55 without any issues. So, readLine()!! can read any type of data and return 55, even if it's not a String?

CodePudding user response:

Actually the 55 you entered is a string and it was printed as string representation also. You couldn't use the 55 to do arithmetic computation eg. 55 - 10 without make it as integer or other number representation like double.

You can check the type like this

if (a is String) {
    print("It's string")
}
  • Related