Search code examples
scalaloopsreturnpattern-matching

Function returns the wrong value only when size of array input is 1


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?


Solution

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