Back to questions
JuniorTheoryCommon
What does the program print?
fun main() {
val n = try {
"42a".toInt()
} catch (e: NumberFormatException) {
-1
}
println(n)
}-1
- Expecting
42: thinkingtoInt()keeps the digits before the letter. It rejects the whole text and throwsNumberFormatException, so thecatchvalue is used. - Expecting a compile error: thinking
trycannot be assigned. Likeif,tryis an expression, and its value is the last line of the block that ran.
- What does the program print if the text is
"42"without the letter? - How would
toIntOrNull()with?:give the same result withouttry?