Wouldn't it be nice to have syntax to allow implic...
# announcements
r
Wouldn't it be nice to have syntax to allow implicit type conversion?
var myInt : Int = ^1L // implicit call toInt() on this Long
or whatever symbol or syntax. Much better than using all sorts of toLong, toInt, toString, toByte etc explicit in code. Losing a lot of the benefits of type inference (if that's the right name)
👌 1
🚫 5
I see some no's, but can anyone add an argument? Java does support it, and the only argument I found for Kotlin to ditch it, is that implicit type conversion could lose precision. By making it explicit to allow this conversion, you give back the option to the developer, and make the code more dynamic. In the example above I could just change myInt to double or String without modifying the explicit conversion (toInt)
t
I'd say that Kotlin philosophy is to not allow implicit code that could be considered "magic", and could cause some nasty hidden bugs or performance issues. By making the conversion explicit, you know that downsizing a
Long
to a
Int
is potentially dangerous (as it could lead to a completely different result). I admit that this is security over comfort, as
toInt()
and
toDouble()
calls harm readability.
I'll add that Kotlin was designed to avoid Java's mistakes. One of the biggest flaw of Java is to implicitely convert `Integer`s to `int`s (auto-unboxing). In case an
Integer
is
null
, implicitly unboxing it would cause a very hard to find
NullPointerException
.
r
It isnt implicit, because you have to add the symbol explicit. But this way you can still use automatic conversion between types, because otherwise you will have cumberstone code. I have my code full of toInt() and toLong() etc, as you said it harms readability, why not let the user make that decision. It will still validate compile time