Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

  scala> "5" + 5
  res0: java.lang.String = 55
Don't use print in the REPL...

> Python gives me a TypeError. And so does Common Lisp. I was expecting the same from Scala

  scala> val i:Int = "5" + 5
  <console>:7: error: type mismatch;
  found   : java.lang.String
  required: Int
       val i:Int = "5" + 5
                       ^
You can easily get a compiler error, if you enforce the type. The inheritance of Javas "I'll call .toString on anything" is definitely not something I'll defend, but it's much less of a problem than it may appear. To do anything interesting with that "fake" integer, you'll have to call a method that only accepts integers - and the compiler will throw an error then. E.g.:

  scala> math.max("5" + 5, 5)
  <console>:8: error: overloaded method value max with alternatives:
    (x: Double,y: Double)Double <and>
    (x: Float,y: Float)Float <and>
    (x: Long,y: Long)Long <and>
    (x: Int,y: Int)Int
   cannot be applied to (java.lang.String, Int)
              math.max("5" + 5, 5)
                   ^


Isn't this something that type inference should catch though?


The type of "5" + 5 is inferred to be String. If you pass it to print(), which takes a String, that's not an error, and printing "55" is presumably what you meant to happen. If you tried to pass it to a method expecting an integer, you'd get an error.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: