Programming Languages – Why Can’t There Be Any Implicit Conversions?

programming-languagestype conversion

As I understand it, implicit conversions can cause errors.

But that doesn't make sense — shouldn't normal conversions also cause errors, then?

Why not have

len(100)

work by the language interpreting (or compiling) it as

len(str(100))

especially since that's the only way (I know of) for it to work. The language knows what the error is, why not fix it?

For this example I used Python, though I feel that for something this small it's basically universal.

Best Answer

For what it's worth, len(str(100)), len(chr(100)) and len(hex(100)) are all different. str is not the only way to make it work, since there's more than one different conversion in Python from an integer to a string. One of them of course is the most common, but it doesn't necessarily go without saying that's the one you meant. An implicit conversion literally means, "it goes without saying".

One of the practical problems with implicit conversions is that it isn't always obvious which conversion will be applied where there are several possibilities, and this results in readers making errors interpreting the code because they fail to figure out the correct implicit conversion. Everyone always says that what they intended is the "obvious interpretation". It's obvious to them because it's what they meant. It might not be obvious to someone else.

This is why (most of the time) Python prefers explicit to implicit, it prefers not to risk it. The main case where Python does do type coercion is in arithmetic. It allows 1 + 1.0 because the alternative would be too annoying to live with, but it doesn't allow 1 + "1" because it thinks you should have to specify whether you mean int("1"), float("1"), ord("1"), str(1) + "1", or something else. It also doesn't allow (1,2,3) + [4,5,6], even though it could define rules to choose a result type, just like it defines rules to choose the result type of 1 + 1.0.

Other languages disagree and do have lots of implicit conversions. The more they include, the less obvious they become. Try memorising the rules from the C standard for "integer promotions" and "usual arithmetic conversions" before breakfast!