shine icon indicating copy to clipboard operation
shine copied to clipboard

Support for type casting

Open romix opened this issue 12 years ago • 2 comments

Here is the idea: Shine should allow to define custom cast operators/functions.

If there is a check somewhere like "o is T1" (e.g. for a function parameter) and it fails at runtime, because the actual value has a different type T, Shine currently issues an error. With this proposal, Shine could try as a fallback to find a cast from T to T1. If it exists, it would apply it and thus satisfy the condition "o is T1".

The search for a cast operator may happen e.g. in the meta-methods of T or T1.

romix avatar Apr 14 '14 09:04 romix

hmm... I could build an __as hook (was planning on doing that anyway), so if you say:

local a = 42 as String

Then you'd get "42" as a string. However, this wouldn't be automatically applied during an is check. I really don't like automatic conversions. Perhaps you can say:

local x as Number = "42"
function log(mesg as String)
   io::stderr.write(mesg)
end

and have the as instead of is in local declarations and parameter lists. I'll think about it.

richardhundt avatar Apr 19 '14 07:04 richardhundt

The idea of using as is not bad. Especially, if you take into account that ìsmay have a fairly mad predicate as its argument, which is not a real class/module/type. In this sense, converting into this something does not make too much sense.as` seems to be more restrictive in this regard, which is good.

But then it could be nice to be able to use both is and as at the same time, where as should probably have a higher priority. The meaning should be then: first convert then check the predicate...

I really don't like automatic conversions.

I can understand. But at the same time, it is widely spread in PLs, tough often misused ;-) One thing, which is sort of nice is that it allows you to pass in types that didn't exist at the time of writing the original code.

But the biggest problem with automatic conversions is that it is so hard to track them and see when they are applied by a compiler/runtime (and I guess it is the main reason you don't like them). If there would be tools/means which would make it easy to see conversions performed at run-time, then they'd become (much more) harmless, IMHO. Most of their black magic would disappear in this case.

romix avatar Apr 19 '14 08:04 romix