I have a function I wrote in Scala which iterates through an array of Option
s. 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?