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...

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay