3 ms·
Why is this preferable to a set of functions that return a particular type? Most uses of such a cast function would be something like cast(unknown_type) <op>
by anonymoushn 12y ago
Why is this preferable to a set of functions that return a particular type? Most uses of such a cast function would be something like
cast(unknown_type) <op> known_type
The programmer could just write tostring or tonumber instead of cast, if the type of the other operand is known >_>
- Pitarou 12y agoAutomatic type casting remains popular because it reduces the syntactic and cognitive overhead. I'm suggesting that a better solution would be to retain explicit casting, but minimise the overheads. So, to take things a step further, lets use, say, the $ operator for casting. Then we have: >>> x = 1 >>> y = "2" >>> print($x + y) 3 >>> print(x + $y) "12" >>> print($x + $y) CastError: ... What do you think?
- mateuszf 12y agoPython example with str and int are IMHO much better. They require only little more typing, but are very readable and explicit.
- danbruc 12y agoThe proper way to do this is using something like TryParse() and ToString() and to handle the case of failing to parse the string as a number and maybe even specifying the locale for both operations. If you are absolutely sure that parsing can not fail you can use Parse() and omit the error handling.