sk1007
sk1007

Reputation: 581

IndexOutOfBoundsException in scala code

I have arraybuffer with 1 or 2 elements: like: ArrayBuffer(Some(one point), Some(two point)) if both elements are available I don't have problem. but Only first element is exist then how to check whether 2nd is exist or not.

I m using like:

if(times.get(1)==null){
 val time = times.get(1)
} else{
 val time = times.get(0)
}

but times.get(1) is throwing IndexOutOfBoundsException when only 1 element is exist.

Upvotes: 0

Views: 1074

Answers (4)

elm
elm

Reputation: 20435

Consider using flatMap as follows,

Array(1,null).flatMap(x => Option(x)).last

or flatten as follows,

Array(Some(1),Option(null)).flatten.last

With the flattening functions we keep only Some values and skim null or None. Note also xs.flatten is in fact xs.flatMap(identity), namely xs.flatMap(x => x)

Upvotes: 0

sbeliakov
sbeliakov

Reputation: 2199

Possible (not very scala like) approach also could be:

If you are sure that at least one object exists you may use scala Try:

val time = Try {
    if (times.get(1) == null) {
        times.get(1)
    } else {
        throw new RuntimeException
    }
} getOrElse times.get(0)

Upvotes: 0

Sascha Kolberg
Sascha Kolberg

Reputation: 7162

As usual in almost any language you can avoid such an exception by checking the size of the collection:

if (times.size >= 2 && times.get(1) == null) times.get(1) else times.get(0)

However, a more scala way to do that for any sized collection would be:

val time = times.reverse.collectFirst { case Some(t) => t }

This will find the last nonEmpty time in your collection and return it as 'Options'.

Upvotes: 1

sbeliakov
sbeliakov

Reputation: 2199

I suggest following snippet

times.filter(_.nonEmpty).map(_.get).lastOption

Let's look closer at every step:

times.filter(_.nonEmpty) filters out empty elements

.map(_.get) maps Some(x) to x, as at this point we're sure that we only have non empty elements

.lastOption returns either Some(x) in case of non empty list where x is last element, either None if list was empty

Upvotes: 0

Related Questions