Knows Not Much Knows Not Much - 1 month ago 10
Scala Question

Scala Equality: Why does this code compile?

There is one particular issue in scala which bites me every time. and each time it bites me ... it bites very hard...

why does this line compile

val x = "10"
if (x != 10) {
print("do something")
}


This line compiles and executes but for a "typesafe" language like scala ... this line should result in an compile error

Answer

Because the ancestor of all types is Any, and Any defines method !=. See http://www.scala-lang.org/api/current/index.html#scala.Any

So the compiler bends backwards to make your code compile, and goes up the type hierarchy of String("10") until it finds an implementation of != that takes an integer

Comments