Skip to main content

Automatic casting

Posted by staufferjames on July 26, 2007 at 4:50 PM PDT

Is there any downside or problem potential to changing the Java compiler to automatically cast? In the example below the result of list.get(0) would automatically be casted to the type of the variable hi (String).

List list = new ArrayList();
list.add("hi");
String hi = list.get(0);
for(Iterator i = list.iterator(); i.hasNext(); ) {
  String item = i.next();//Automatic casts
  System.out.println(item);
}
//Or using the new for construct:
for(String item : list) {
  System.out.println(item);
}

I know that generics allow you to reduce casting but they do so at the expense of making declaration more difficult. To me, the benefit of generics is that they allow you to have the complier enforce more rules -- not they they reduce casting (but I haven't used them much so I am somewhat uninformed). This proposal would only reduce the amount of code to type, not move it to another place.


http://weblogs.java.net/blog/emcmanus/archive/2007/03/getting_rid_of.html
shows that the compiler can get really close. Why can't it go the rest of the way?

Clarification update: The automatic casting would only be done with the type on the left hand side of the assignment is a sub-class of the type on the right hand side of the assignment.

Clarification update: The following examples might show the need for this better:

List list = new ArrayList();
list.add(new Integer(1234));
list.add("+");
list.add(new Integer(1000));

for(Object item : list) {
  if(Object instanceof String) {
    String str = object;
    //do something
  } else if(Object instanceof Integer) {
    Integer integer = object;
    //do something else
  } else {
    //error
  }
}

//Another separate example:
public Person create(int id) {
  //read DB record
  if(isMale) {
    return new Male(blah)
  } else(isFemale) {
    return new Female(blah)
  } else {
    //error
  }
}

doIt {
  Male me = create(myId);
}
Related Topics >>