Created
February 5, 2017 00:27
-
-
Save dariusf/8cdc42897a791a5fdabbd315b8d0bb28 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
| class Files { | |
| static void read(File<Open> file) {} | |
| static File<Open> open(File<Closed> file) { | |
| return null; | |
| } | |
| static File<Closed> close(File<Open> file) { | |
| return null; | |
| } | |
| } | |
| interface State {} | |
| class Open implements State { | |
| private Open() {} | |
| } | |
| class Closed implements State { | |
| private Closed() {} | |
| } | |
| class File<S extends State> { | |
| static File<Closed> create() { | |
| return null; | |
| } | |
| } | |
| public class Bikeshed { | |
| public static void main(String[] args) { | |
| File<Closed> file = File.create(); | |
| // Does not compile | |
| File<Integer> a = null; | |
| // Does not compile | |
| Files.close(file); | |
| File<Open> openFile = Files.open(file); | |
| Files.read(openFile); | |
| File<Closed> closedFile = Files.close(openFile); | |
| // Does not compile | |
| Files.read(closedFile); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment