Last active
January 14, 2017 02:15
-
-
Save weidagang/a46512394d01206b0b3515805ab84921 to your computer and use it in GitHub Desktop.
Simulating Haskell typeclass with Java generic interface.
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
// Simulating Haskell typeclass with Java generic interface. | |
public class Main { | |
public static void main(String[] args) { | |
MyInt i1 = new MyInt(1); | |
MyInt i2 = new MyInt(2); | |
MyInt i3 = i1.add(i2); | |
System.out.println(i3); // "3" | |
MyString s1 = new MyString("1"); | |
MyString s2 = new MyString("2"); | |
MyString s3 = s1.add(s2); | |
System.out.println(s3); // "12" | |
i3 = Adder.add(i1, i2); | |
System.out.println(i3); // "3" | |
s3 = Adder.add(s1, s2); | |
System.out.println(s3); // "12" | |
} | |
} | |
interface Addable<T extends Addable<T>> { | |
T add(T another); | |
} | |
class Adder { | |
public static <T extends Addable<T>> T add(T t1, T t2) { | |
return t1.add(t2); | |
} | |
} | |
class MyInt implements Addable<MyInt> { | |
private int value; | |
public MyInt(int value) { | |
this.value = value; | |
} | |
@Override | |
public MyInt add(MyInt another) { | |
return new MyInt(this.value + another.value); | |
} | |
@Override | |
public String toString() { | |
return Integer.toString(value); | |
} | |
} | |
class MyString implements Addable<MyString> { | |
private String value; | |
public MyString(String value) { | |
this.value = value; | |
} | |
@Override | |
public MyString add(MyString another) { | |
return new MyString(this.value + another.value); | |
} | |
@Override | |
public String toString() { | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment