[407] in java-interest
Re: Request for feature: type casing
daemon@ATHENA.MIT.EDU (Arthur van Hoff)
Tue Jun 20 13:23:11 1995
From: Arthur.Vanhoff@Eng.Sun.COM (Arthur van Hoff)
To: majordom@java.Eng.Sun.COM (Simon Spero)
Date: Tue, 20 Jun 1995 10:00:11 -0800 (PDT)
Cc: java-interest@java.Eng.Sun.COM
In-Reply-To: <Pine.SOL.3.91.950619194932.13041B-100000@chivalry> from "Simon Spero" at Jun 19, 95 08:04:18 pm
Hi Simon,
> I've been working on some code that uses sub-classing to hold different
> flavour requests that are parsed from a stream. There are some methods
> that are specialed for each class, but in general sub-classing is being
> used instead of old-fashioned unions (this is the 90s, dammit).
>
> As is usually the case, there's a feature from lisp/clos that would make
> this much easier; however unlike normal, the feature can be implemented
> pretty easily without any overhead.
>
> What I'd like to be able to do is something like:
>
> class anObject {}
> class anInt extends anObject {public int i;}
> class aString extends anObject {public String s;}
>
> ....
> anObject o = foo.parse(System.in);
>
> typecase(o) {
> case anInt:
> total += o.i;
> break;
> case aString:
> System.out.println(o.s);
> break;
> default:
> throw(new RealityFailure_RebootUniverse());
> }
>
> This code can be defined in terms of existing control structures-
>
> anObject tmp = o;
> if(tmp instanceof anInt) {
> anInt o = (anInt)tmp;
> total += o.i;
> } else if(tmp instanceof aString) {
> aString o = (aString)tmp;
> System.out.println(o.s);
> } else {
> throw new RealityFailure_Reboot_Universe();
> }
>
> The second form is a lot denser and harder to read; surely there's room
> for just one bit of syntactic sweet and low in java yet (hmmm - though if
> we had macros, we could add this ourselves :-)
We've been considering a 'typecase' statement for a while. It makes
a lot of sense to have one. I don't think you could implement it using
a macro's though, the type of the variable has to be changed inside
the type cases. Also, using something similar to a 'switch' statement
is not a good idea because you can't fall through into the next case.
Have fun,
Arthur van Hoff (avh@eng.sun.com)
http://java.sun.com/people/avh/
Sun Microsystems Inc, M/S UPAL02-301,
100 Hamilton Avenue, Palo Alto CA 94301, USA
Tel: +1 415 473 7242, Fax: +1 415 473 7104
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com