3

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

3
  • 1
    You should look at scalaz === operator to get what you want. stackoverflow.com/a/30243825/4080476 Commented Oct 27, 2016 at 21:46
  • 1
    Why do you think it should not compile? 10 does not equal to "10", so the result you are getting is correct. Why do you think it should be impossible to compare objects of different types? Commented Oct 27, 2016 at 22:24
  • == is simply a method, not an operator, how would you do it differently? Commented Oct 27, 2016 at 22:27

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Pattern matching gives you a bit more help.

scala> val i = 17 i: Int = 17 scala> "42" match { case `i` => } <console>:13: error: type mismatch; found : Int required: String "42" match { case `i` => } ^ scala> case class C(i: Int) defined class C scala> 42 match { case C(_) => } <console>:14: error: constructor cannot be instantiated to expected type; found : C required: Int 42 match { case C(_) => } ^ 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.