Skip to content

Instantly share code, notes, and snippets.

@bkyrlach
Created April 26, 2013 19:19
Show Gist options
  • Save bkyrlach/5469688 to your computer and use it in GitHub Desktop.
Save bkyrlach/5469688 to your computer and use it in GitHub Desktop.
Idea for type class in Java (not type safe)...
public interface Show<A> {
String apply(A a);
}
public class ShowInteger implements Show<Integer> {
@Override
public String apply(Integer a) {
return a.toString();
}
}
public class ShowList implements Show<List>{
@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>>();
static {
Map<Class, Object> shows = new HashMap<Class, Object>();
shows.put(Integer.class, new ShowInteger());
shows.put(ArrayList.class, new ShowList());
tcs.put(Show.class, shows);
}
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");
Show<Integer> s = TypeClassFactory.implicitly(Show.class, a);
System.out.println(s.apply(a));
Show<List<String>> s1 = TypeClassFactory.implicitly(Show.class, l);
System.out.println(s1.apply(l));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment