Created
June 12, 2012 19:34
-
-
Save gclaramunt/2919649 to your computer and use it in GitHub Desktop.
Phantom types in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AirTrafficController { | |
public static Plane<Landed> land(Plane<Flying> p) { | |
return new Plane<Landed>(p); | |
} | |
public static Plane<Flying> takeOff(Plane<Landed> p) { | |
return new Plane<Flying>(p); | |
} | |
public static void main(String[] args){ | |
Plane<Landed> p=Plane.newPlane(); | |
Plane<Flying> fly=takeOff(p); | |
Plane<Landed> land=land(fly); | |
//doesn't compile: | |
//Plane<Landed> reallyLanded=land(land); | |
//Plane<Flying> reallyFlying=takeOff(fly); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface FlightStatus { | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Flying extends FlightStatus{ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Landed extends FlightStatus { | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Plane<Status extends FlightStatus> { | |
private Plane(){ | |
// blah blah blah | |
} | |
public Plane(Plane<? extends FlightStatus > p){ | |
//copy whatever info we need | |
} | |
public static Plane<Landed> newPlane(){ | |
return new Plane<Landed>(); | |
} | |
} |
yeah, private is a good idea.
I thought also on making Status extend a common FlightStatus
There you go...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably should have private constructor so Planes can't be created in any old state.