Skip to content

Instantly share code, notes, and snippets.

@ckirkendall
Forked from bkyrlach/Show.java
Last active December 16, 2015 17:38
Show Gist options
  • Save ckirkendall/5471370 to your computer and use it in GitHub Desktop.
Save ckirkendall/5471370 to your computer and use it in GitHub Desktop.
abstract class Show<A> {
public static register(Class c, Show s){
Map<Class,Object> shows=TypeClassFactory.tcs.get(Show.class)
if(shows!=null){
shows.put(c,s);
}else{
shows = new Map<Class,Object>();
shows.put(c,s);
TypeClassFactory.tcs.put(Show.class, shows);
}
}
public static show(A a){
Show<A> tmp=TypeClassFactory.implicitly(Show.class, a);
tmp.apply(a)
}
String apply(A a);
}
public class ShowInteger implements Show<Integer> {
static{
Show.register(Integer.class, new ShowInteger());
}
@Override
public String apply(Integer a) {
return a.toString();
}
}
public class ShowList implements Show<List>{
static{
Show.register(ArrayList.class, new ShowList());
}
@Override
public String apply(List a) {
StringBuffer sb = new StringBuffer();
sb.append("List(");
for(int i = 0; i < a.size(); i++) {
sb.append(a.get(i));
sb.append(", ");
}
if(!a.isEmpty()) {
sb.delete(sb.length() - 2, sb.length());
}
sb.append(")");
return sb.toString();
}
}
public class TypeClassFactory {
private static final Map<Class, Map<Class, Object>> tcs = new HashMap<Class, Map<Class, Object>>();
public static <TC, A> TC implicitly(Class typeClass, A fr) {
return (TC)tcs.get(typeClass).get(fr.getClass());
}
}
public class ImplicitProgram {
public static void main(String[] args) {
Integer a = 123;
List<String> l = new ArrayList<String>();
l.add("abc");
l.add("def");
l.add("ghi");
System.out.println(Show.show(a));
System.out.println(Show.show(a));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment