[403] in java-interest

home help back first fref pref prev next nref lref last post

Request for feature: type casing

daemon@ATHENA.MIT.EDU (Simon Spero)
Mon Jun 19 23:25:08 1995

Date: Mon, 19 Jun 1995 20:04:18 -0700 (PDT)
From: Simon Spero <ses@tipper.oit.unc.edu>
To: Java Interest Mailing List <java-interest@java.sun.com>

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 :-)

Simon

-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post