6 June 2013

Scala notes 5 : compare is weird in scala

Information: THIS IS NOT TUTORIAL.
Scala notes is series of my "side comments" that can be useful during learning Scala.
Their contains bunch of information about interesting bits, explanation of things that i didn't come across yet or attempt to explain things which i didn't understand.


WOW!

Learning Scala is a weird for me .I feel it is not logical and not intuitive from time to time.

I discover today, that  Scala allow you to compare  incomparable types  even if result will be always  false (well, actually according to Scala ... most likely,which is even more scary) .
you can do stupid things and compiler will not complain or ... just display warning.

Look on this example

Example 1. this code will compile without warning

if (1.toString() == 1) { // <- weird,but you can do something like that ...
   println("Comiler will compile this code and to make things more funny without any warning! btw. this will never return ... true,lol")
}
Example 2. this code will compile but it will display warning  in IDE

val i = 1
val w = "1"
if (i == w) { // <- weird,but you can do something like that ...
  println("this comparison will always return false,but... ")
}

Warning which you will see is bit scare:

Multiple markers at this line
 - comparing values of types Int and String using `==' will always yield false
 - Int and String are unrelated: they will most likely never compare  equal

 Most likely is not mean always,so it  can be a weird unexpected case,when this 2 things are equal.
Imagine how this can screw up your life if write application  that is for medical application , nuclear plant or bank and by accident you do this kind of mistake (mistype ) ...
I don't like this kind of behave of compiler...

Example 3: Java behave much better:
if you type:

if("1" == 1){
   System.out.println("You can't do that in java");
}

You will see error(not warning): "incomparable types: String and int" which is expected , intuitive and logical  ...

I know flexibility come with responsibility but ... humans are not error proof,so compiler is a tool that should do not allow that to prevent accidental mistakes.At least this is my opinion.

No comments:

Post a Comment