The program is:
object Hello extends App {
val a: List[Int] = List(1, 3, 4, 5, 8, 10, 11, 22, 33)
for (i <- 0 to 11)
println(a(i))
}
The Output is:
1
3
4
5
8
10
11
22
33
java.lang.IndexOutOfBoundsException: 9 // continues as a long error message.
How did it not detect at the compile time that the index was going to be out of bound? Aren't compiled languages supposed to do this? If no, could you please share what is included in the compile time checks and what's not?
As a newbie, I always hear that, compiled languages are great that they find errors at compile time thus are more robust.
The main problem here is that
for
in Scala does not mean the same as it does in other languages. The code in the question is equivalent toThe compiler would have to inspect a number of different methods and infer their behaviour in order to determine that the
apply
method would throw an exception.But the main advantage of compiled languages is performance, not error checking. It is strongly-typed languages (which are typically compiled) that provide better error detection.