How to convert a String to a Long in Kotlin? Safe ways and error handling
Hello colleagues! I just started learning Kotlin (migrated from Java) and encountered a seemingly simple task. I need to read a user ID from a text field in the application (it's a string) and pass it to a function that expects a Long.
In Java, I usually used `Long.parseLong(str)` or `Long.valueOf(str)`, wrapping it in a try-catch. But in Kotlin, I see several different methods: `.toLong()`, `.toLongOrNull()`, some extension functions... And I'm confused about which one is correct and safe.
Here's an example of my code that currently crashes with an exception:
```kotlin
fun main() {
val userInput: String = "123abc" // user accidentally entered letters
val userId: Long = userInput.toLong() // NumberFormatException!
println("User ID: $userId")
}
```
I understand that
No answers yet.
Log in to leave an answer