Created
November 4, 2017 22:06
-
-
Save pablogrisafi1975/31b1e75ec983f173513d6061517ab093 to your computer and use it in GitHub Desktop.
Lists with compile time check over length
This file contains 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
import java.util.Arrays; | |
import java.util.List; | |
public class Main { | |
static abstract class Num{ | |
public abstract int n(); | |
static class N0 extends N1{ | |
@Override | |
public int n() { | |
return 0; | |
} | |
} | |
static class N1 extends N2 { | |
@Override | |
public int n() { | |
return 1; | |
} | |
} | |
static class N2 extends N3{ | |
@Override | |
public int n() { | |
return 2; | |
} | |
} | |
static class N3 extends Num{ | |
@Override | |
public int n() { | |
return 3; | |
} | |
} | |
private static final N0 N0 = new N0(); | |
private static final N1 N1 = new N1(); | |
private static final N2 N2 = new N2(); | |
private static final N3 N3 = new N3(); | |
} | |
static class NList<N extends Num, E>{ | |
private final List<E> elementList; | |
public <NN extends N> E get(NN n){ | |
return elementList.get(n.n()); | |
} | |
public NList(E... es) { | |
this.elementList = Arrays.asList(es); | |
} | |
public static <EE> NList<Num.N0, EE> of(EE e0){ | |
return new NList<Num.N0, EE>(e0); | |
} | |
public static <EE> NList<Num.N1, EE> of(EE e0, EE e1){ | |
return new NList<Num.N1, EE>(e0, e1); | |
} | |
public static <EE> NList<Num.N2, EE> of(EE e0, EE e1, EE e2){ | |
return new NList<Num.N2, EE>(e0, e1, e2); | |
} | |
public static <EE> NList<Num.N3, EE> of(EE e0, EE e1, EE e2, EE e3){ | |
return new NList<Num.N3, EE>(e0, e1, e2, e3); | |
} | |
} | |
public static void main(String... args){ | |
NList<Num.N1, String> l1 = NList.of("a", "b"); | |
l1.get(Num.N0); | |
l1.get(Num.N1); | |
//l1.get(Num.N2); // does not compile | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment