automatic int to short conversion - the HELL?

Bill Baxter wbaxter at gmail.com
Thu Sep 18 14:07:22 PDT 2008


On Fri, Sep 19, 2008 at 4:05 AM, Ary Borenszweig <ary at esperanto.org.ar> wrote:
> Chris R. Miller wrote:
> No, no. In Java it's an error, an explicit cast is required.
>
> http://www.programmersheaven.com/2/FAQ-JAVA-Type-Conversion-Casting
>
> Which is perfect. It expresses the intents of the programmer:
>
> long x = ...;
> int y = (int) x; // yes, I know I might loose information, but I'm sure
>                 // it won't happen
>

Well, I wouldn't say it *perfectly* expresses the programmer's intent.
 I doubt the programmer really intended to say "I want to pretend x is
an int no mater what its actual type is".

By which I mean to say a better expression of the user's intent would
be "I want to convert x into an integer so long as it is a type for
which the compiler knows how to convert".  I.e. I don't want to
accidentally try to convert an array or something like that to an int.

Or maybe that's not an issue in Java?  Maybe it doesn't let you cast
arbitrary things to ints.  But anyway D's cast is not like that, so
the same solution needs tweaking to port to D.  Like some kind of
conversion cast that's distinct from the generic coercive cast.  I
suppose that's basically what the modules like std.conv aim to
provide.  An alternate kind of cast.  to!(int)(x) instead of
cast(int)x.

--bb


More information about the Digitalmars-d-learn mailing list