3

I have a function I wrote in Scala which iterates through an array of Options. I wish to return the first index for which the option is not None. My code works alright for all arrays of length greater than 1. It doesn't, however, work for arrays of size 1.

This is my existing code

def firstSome(): Int = {
    for (i <- 0 until this.arr.length - 1) {
        this.arr(i) match {
            case Some(_) => {
                println("Returns")
                return i
            }
            case None => // do nothing
        }
    }
    println("Oops")
    return -1
}

For some reason, both Returns and Oops are printed out. I'd thought that the function will return i after going to the Some case, but somehow it continues despite the return statement.

I've also printed out this.arr and confirmed that element inside the array is not None.

Any idea what's the issue?

absolutelydevastated
  • 1,657
  • 1
  • 11
  • 28
  • 2
    on a sidenote, you should never use return in Scala for the following reasons: https://tpolecat.github.io/2014/05/09/return.html – mutantacule May 18 '19 at 18:59

2 Answers2

3

0 until x is the range from 0 to x - 1. So there is an off by one error in your for, it should be correctly:

    for (i <- 0 until this.arr.length) {
       ...
    }

As the use of return in Scala is highly discouraged, I'd like to point out the find method to you, which does exactly what you are trying to implement here.

mutantacule
  • 6,913
  • 1
  • 25
  • 39
2

An alternative to writing a custom loop would be to use indexWhere method like so

arr.indexWhere { 
  case Some(_) => true
  case None => false
}

which would also work out-of-the-box for array of length 1.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98