Knows Not Much Knows Not Much - 2 months ago 17
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


Because the ancestor of all types is Any, and Any defines method !=. See

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