Hello GFP
Hello GFP

Reputation: 3

What happens with toInt()

I currently start to learn Kotlin and I was making this code

val a =  "1"
val b = a[0]
val c = b.toInt()
println(c)

When I run the code, the result is 49. What really happened? Because I think the result will be 1.

Upvotes: 0

Views: 661

Answers (3)

Roland
Roland

Reputation: 23262

a is a String, which is a CharSequence. That is why you can access a[0] in the first place. a.get(0) or a[0] then returns a Char. Char on the other hand returns its character value when calling toInt(), check also the documentation of toInt().

So your code commented:

val a =  "1" // a is a String
val b = a[0] // b is a Char
val c = b.toInt() // c is (an Int representing) the character value of b

If you just want to return the number you rather need to parse it or use any of the answers you like the most of: How do I convert a Char to Int? (one simple way being b.toString().toInt()).

Upvotes: 2

dey
dey

Reputation: 3140

In your example a is a String, but String. String is under the hood an Array of Char. And by accessing your String using a[0] operator, you get first element of this Char Array. So you get Char '1', not String "1". And now, when you run '1'.toInt() function on Char - it will return ASCII code of that Char. When you run "1".toInt() on String - it will convert this String into Int "1". When you need to get Int value of first letter in your String, you need to convert it first into String:

val a = "123"
val b = a[0].toString() // returns first Char of String "123" and converts to String
val c = b.toInt()       // returns Int: 1

or in one line:

"123"[0].toString().toInt()

Upvotes: 0

max
max

Reputation: 6187

a is String,
when you get a[index] return type is char,
in kotlin char.toInt method return ASCII code of the character and it's 49

if you want to get the integer value of "1" just use toString method

val a =  "1"
val b = a[0].toString()
val c = b.toInt()       
println(c)

prints:1

Upvotes: 0

Related Questions