No Covariant Return Types

[Voting on JavaDesignFlaws page.]

This design flaw is described in the JavaBugDatabase in the entry 4144488. The problem is that a method may not be overridden with a different return type, even if the new return type is assignable to the original one.

As an example, the following code is invalid:

 public ThisClass clone(){
return (ThisClass)super.clone();
 }
Of course, there is no inherent reason for this code to be invalid, as clone() still returns an Object.

The JavaLanguage now has support for CovariantReturnTypes as of the 1.5 JDK, which is currently in beta. It was introduced as part of generics support, JSR-014.


Interesting that if Java were to change to have covariant return types (a possible change I am open to), then ChoiceOperatorDoesNotConsiderInheritance is a non-issue, you can just do the following:

  SerialLink createLink() {
return new SerialLink();
  }

TcpLink createLink() { return new TcpLink(); }

because the two classes are both CommsLink. --StevenNewton

Covariant return types would have no effect on ChoiceOperatorDoesNotConsiderInheritance, as the semantics of the choice operator is currently defined.


How many languages with StaticTyping do have CovariantReturnTypes? This is only fairly recent in C++ and not supported by many compilers. So it can't be a frequently used technique in that language. It's not recent in C++, because it was in the Standard when it was technically finished in 1997, before publication in 1998. It's supported by all compilers I've used except MSVC++6. IIRC Eiffel also has covariant return types. --JamesDennett


Languages with CovariantReturnTypes


Sidenote. This problem is solved in GJ: one of the proposals to add generics to Java. The way they handled it makes it seem that it would not be too hard to fix.

Return types are a hack anyway. Is there a problem using OUT style parameters? They make more sense than overloading the 'C' status return with yet more functionality.

I've always viewed OUT style parameters as a CodeSmell - and you can bet your bottom dollar that they soon morph into IN/OUT parameters, which are of course the SpawnOfTheDevil?. Parameters should go in one side and come out the other. A lot of languages lack tuples, and so people grow up not knowing any better.

// CeePlusPlus using the BoostLibraries
tie( x, y, z ) = position[ "robot" ];

What about return values for overloaded operators?

I agree you lose a lot of desirable syntactic sugar. I may well be completely missing the point, plus there may be an issue of multiple dispatch; but if we assume that returns are handled by passing a reference parameter, can't we do the same thing using standard overloading, but ugly? Or is there a fundamental problem?

I was just worried about ugliness myself. It's nice to be able to write x = y + z instead of add(&x, y, z).


CategoryJava


EditText of this page (last edited December 28, 2005) or FindPage with title or text search