General issues

Here is the relevant code:

public interface Artifact {} public interface Bundle implements Artifact {} public interface Component implements Artifact {} public interface State<T extends Artifact> { void transition(T artifact, State<T> nextState); } 

This allows me to define this enumeration:

 enum BundleState implements State<Bundle> { A, B, C; public void transition(Bundle bundle, State<Bundle> nextState) {} } } 

But the signature of the method I want is:

  public void transition(Bundle bundle, BundleState nextState) {} } 

But this does not compile. Obviously, the problem is how I defined T in the State interface, but I cannot figure out how to fix this.

Thanks Don

+4
source share
4 answers

Things may start with inconvenience, but you can change State to:

 public interface State<T extends Artifact, U extends State<T, U>> { void transition(T artifact, U nextState); } 

And change the BundleState to:

 public enum BundleState implements State<Bundle, BundleState> { A, B, C; public void transition(Bundle bundle, BundleState nextState) {} } 
+10
source

Methods are not contravariant in Java. You can overload and have both, but there wouldnโ€™t be much point.

Perhaps you could declare State as something like:

 public interface State<THIS extends State<THIS, A>, A extends Artifact> { void transition(A artifact, THIS nextState); } 

THIS extends State<THIS, A> may be incorrect. It depends on what you want to do.

(Monomial enumeration constants are probably bad ideas, especially when mixed with generics parameters.)

+3
source

(Bundle, BundleState) does not match your current state interface unless you change it as suggested by others. You can also save the interface with

 enum BundleState implements Artifact, State<BundleState> { A, B, C; public void transition(BundleState bundle, State<BundleState> nextState) { } } 
+1
source
 enum BundleState implements State<Bundle> { A, B, C; public void transition(Bundle bundle, BundleState nextState) { transition(bundel, (State<Bundle>)nextState); } public void transition(Bundle bundle, State<Bundle> nextState) {} } 
0
source

All Articles