Hacker News new | ask | show | jobs
by FascinatedBox 3136 days ago
This is possible exactly because Java is statically-typed. Java's type system works over the operands, and does implicit conversions before the expression gets a chance to run. It sees values and does implicit magic from left to right.

Python, on the other hand, does not need to do a typing pass at parse-time. Instead, literals are stored as values, and those values are tagged with their source class. Python's way of doing it means that a + operation is called upon with an integer and a string.

Java might be able to yield the same kind of result as Python if it had operator overloading. It could define Integer's + operator as only taking other Integer values, therein yielding a type error at parse-time.

My own language uses ++ instead of + to distinguish between addition and concatenation, though I've considered some other token since the two are quite similar to each other.

3 comments

Actually Python does have a way to change addition semantics. It's just not defined for this operation.
> This is possible exactly because Java is statically-typed.

Are you saying that Python can't make "a"+1 become "a1" because it lacks static typing? That's not true. If they wanted to, they could have added an overload for the string+integer case.

> Java might be able to yield the same kind of result as Python if it had operator overloading.

Not necessary. They would have just had to omit the built-in overload for string+integer (and perhaps also for string+object, given the newish auto-boxing feature).

This has literally nothing to do with static typing. It is 100% due to implicit promotion (demotion?) of addition operands to string if either operand is a string.

All static typing does is mean that the type check, and so decision to insert the conversion call is done at compile time. Dynamic typing just means that the type check and decision to insert the conversion is done at the point the + is evaluated.