DEV Community

Cover image for Don't use .first() without handling exceptions
Enieber Cunha
Enieber Cunha

Posted on

Don't use .first() without handling exceptions

When you work with kotlin is much common you need get first caracter of string. So you need function stringVariable.first().

The problem occorer when you not handling execption of this methods, like NoSuchElementException.

So use the try cat and not use in if like:

val name = "Kotlin"
if (name.first() == "K") {
...
Enter fullscreen mode Exit fullscreen mode

if you change the name value to another has exception: NoSuchElementException or NoSuchElementException when send crash you app.

Top comments (1)

Collapse
 
vanhine profile image
Adam Van Hine

First should only throw if the string is empty. So you could also check to make sure it wasn't empty to avoid the exception. kotlinlang.org/api/latest/jvm/stdl...