Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Equality: Why does this code compile?

Tags:

scala

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

like image 295
Knows Not Much Avatar asked Mar 10 '26 02:03

Knows Not Much


1 Answers

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

like image 127
radumanolescu Avatar answered Mar 13 '26 08:03

radumanolescu