What if your program could magically turn words into numbers and do math instantly?
Why String to number conversion in Kotlin? - Purpose & Use Cases
Imagine you receive a list of numbers as text from a friend, like "123", "456", and "789". You want to add them up, but they are all words, not real numbers.
Trying to add these text numbers directly will just join them like words, not add their values. Doing the math by hand or rewriting each as a number is slow and easy to mess up.
String to number conversion lets you turn those text numbers into real numbers quickly and safely, so you can do math with them just like normal numbers.
val sum = "123" + "456" // results in "123456"
val sum = "123".toInt() + "456".toInt() // results in 579
This lets you work with numbers that come as text from anywhere, like user input or files, and do real calculations with them.
When you build a calculator app, users type numbers as text. You convert those texts to numbers to add, subtract, or multiply them correctly.
Text that looks like numbers can't be used in math until converted.
Manual math on text is slow and error-prone.
String to number conversion makes math with text easy and reliable.
Practice
String to an Int?Solution
Step 1: Understand the conversion functions
Kotlin providestoInt()to convert strings to integers,toDouble()for doubles, andtoString()converts other types to strings.Step 2: Identify the correct function for String to Int
Since the question asks for converting aStringto anInt,toInt()is the correct function.Final Answer:
toInt() -> Option DQuick Check:
String to Int = toInt() [OK]
- Confusing toInt() with toString()
- Using toDouble() when integer is needed
- Trying to convert non-numeric strings without error handling
"123" to an integer?Solution
Step 1: Check Kotlin syntax for string to int conversion
The correct syntax is callingtoInt()on the string object, like"123".toInt().Step 2: Analyze each option
val num = "123".toInt() uses the correct method call. Options B and C are invalid function calls in Kotlin. val num = "123".toInteger() uses a non-existent methodtoInteger().Final Answer:
val num = "123".toInt() -> Option CQuick Check:
Correct syntax = "123".toInt() [OK]
- Trying to call toInt() as a standalone function
- Using Java-like Integer.parseInt() syntax
- Using non-existent methods like toInteger()
val s = "45" val n = s.toInt() + 10 println(n)
Solution
Step 1: Convert string to integer and add
The string "45" is converted to integer 45 usingtoInt(). Then 10 is added, resulting in 55.Step 2: Print the result
Theprintln(n)outputs the integer 55, not string concatenation.Final Answer:
55 -> Option AQuick Check:
45 + 10 = 55 [OK]
- Thinking + concatenates strings here
- Expecting output '4510' instead of 55
- Ignoring toInt() conversion effect
val s = "abc" val n = s.toInt() println(n)
Solution
Step 1: Understand toInt() behavior on invalid strings
CallingtoInt()on a string that is not a valid number throws aNumberFormatExceptionat runtime.Step 2: Analyze the given string "abc"
Since "abc" cannot be converted to an integer, the program will crash with a runtime exception.Final Answer:
Runtime exception due to invalid number format -> Option BQuick Check:
Invalid string toInt() causes runtime error [OK]
- Expecting toInt() to return 0 for invalid strings
- Thinking toInt() throws compile-time error
- Ignoring exception possibility
listOf("10", "20", "abc", "30"). Which Kotlin code safely converts valid strings to integers and ignores invalid ones?Solution
Step 1: Understand safe conversion with toIntOrNull()
toIntOrNull()returns null if conversion fails, avoiding exceptions.Step 2: Use mapNotNull to convert and skip nulls
mapNotNull { it.toIntOrNull() }converts valid strings and removes nulls from invalid ones.Step 3: Analyze other options
list.map { it.toInt() } throws exception on "abc". list.filter { it.toInt() > 0 } tries to convert without safety and filters by value, causing error. list.filterNotNull().map { it.toInt() } filters non-null strings but does not handle invalid numbers.Final Answer:
list.mapNotNull { it.toIntOrNull() } -> Option AQuick Check:
Safe conversion uses toIntOrNull() + mapNotNull [OK]
- Using toInt() directly causing exceptions
- Filtering strings before conversion incorrectly
- Not handling null results from toIntOrNull()
Ready to prove it?
Pass the test and this pattern moves unknown
