Kotlin tips #1 : Avoid ArrayOutOfBoundException

Julien Piatek
Sep 9, 2018 · 1 min read

Hey ! I found a very useful Kotlin function recently :

No need to check by hand if the position is within the array bound, now you can process like below :

Okay, let me show you another one. Now what if you want to put fruits[position] in a val, and want a default value if the position is out of bound ?

Here is what is gives with our previous example:

As you can see, the second argument is a lambda function, allowing you to do something depending on the position:

I hope this will helps you to write more concise code with Kotlin !

Cheers

Julien Piatek

Written by

Kotlin/Android/Firebase ❤️ Still learning

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade