Created
April 26, 2013 19:19
-
-
Save bkyrlach/5469688 to your computer and use it in GitHub Desktop.
Idea for type class in Java (not type safe)...
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
public interface Show<A> { | |
String apply(A a); | |
} |
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
public class ShowInteger implements Show<Integer> { | |
@Override | |
public String apply(Integer a) { | |
return a.toString(); | |
} | |
} |
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
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(); | |
} | |
} |
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
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()); | |
} | |
} |
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
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