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

Some things to note:

I think you're mixing casts and conversions. At least in the parlance that I'm used to, you can only cast a number to a String or a String to a number in a memory-unsafe language (and it's rarely what you want and a bit dangerous). When you do this, the system will take your word that the data is actually a String and interpret those literal bits in memory as one. In a memory-safe language, this cast would, of course, likely raise an exception. In Scala, you can cast any object to any type with that object's asInstanceOf method.

In Scala (and many other languages), you can convert numbers to Strings and back. In fact, any object can be converted to a String via that object's toString method (which every object has as a quirk inherited from Java). Strings can also be converted to numbers via toX methods (e.g. toInt, toFloat, etc.). Of course, these conversions will raise exceptions if the content of the String does not match the format of the numeric type you are converting to.

This all matters because it is how the + method on String works: it doesn't (unsafely) cast its argument to a String. Rather, it (safely) converts it via its toString method. You may dislike the idea this method exists (I certainly do, and wish it could be deprecated now that Scala has String interpolation), but it is just a method that happens to be defined on the standard library's String type and not a major defeat of the type system.



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

Search: