As far as I know, the isDefinedAt method should work like types contains method. But strangely enough, it behaves differently – it does not check elements for repeated occurence.
val randomizer = new Random
def next(acc: List[Int], n: Int): List[Int] = {
if(n > 0) {
val r = randomizer.nextInt(15)
println("generating, r=" + r + " is defined=" + acc.isDefinedAt(r))
if(!acc.isDefinedAt(r)) next(r :: acc, n - 1) // check for NO coincidence
else next(acc, n)
} else acc
}
println("indices = " + next(List[Int](), 6))
Ofcourse, I can use Sets for that instead of lists, but nevertheless, why does it act like this?
The output that I get is like
generating, r=8 is defined=false
generating, r=13 is defined=false
generating, r=2 is defined=false
generating, r=8 is defined=false
generating, r=9 is defined=false
generating, r=3 is defined=true
generating, r=2 is defined=true
generating, r=7 is defined=false
indices = List(7, 9, 8, 2, 13, 8)
All
isDefinedAtdoes is tell you if a function does not accept an argument. That is, ifisDefinedAtreturnsfalse, then you know the function doesn’t cover that value. Fortrue, it may cover the value or throw an exception.In the specific case of
List(and allSeq),isDefinedAt(i)will return true if0 <= i < list.size, and false otherwise, andlist(i)will only throw an exception ifisDefinedAt(i)returns false.Anyway, let’s try it out: