Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Force operations on same money currencies in Java at compile time.

View MoneyTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
package ro.igstan.playground;
 
import java.util.ArrayList;
import java.util.List;
 
public class MoneyTest {
 
public static interface Money<E extends Money<E>> {
public static final class Zero<E extends Money<E>> implements Money<E> {
@Override
public Money<E> add(Money<E> a) {
return a;
}
 
@Override
public Number amount() {
return 0;
}
}
 
Money<E> add(Money<E> a);
 
Number amount();
}
 
public static class USD implements Money<USD> {
private final Integer amount;
 
public USD(Integer amount) {
this.amount = amount;
}
 
@Override
public Money<USD> add(Money<USD> a) {
return new USD(amount().intValue() + a.amount().intValue());
}
 
@Override
public Integer amount() {
return amount;
}
}
 
public static class EUR implements Money<EUR> {
private final Integer amount;
 
public EUR(Integer amount) {
this.amount = amount;
}
 
@Override
public Money<EUR> add(Money<EUR> other) {
return new EUR(this.amount().intValue() + other.amount().intValue());
}
 
@Override
public Integer amount() {
return amount;
}
}
 
public static <E extends Money<E>> Money<E> sum(List<E> moneyList) {
Money<E> total = new Money.Zero<E>();
 
for (Money<E> money : moneyList) {
total = total.add(money);
}
 
return total;
}
 
public static void main(String[] args) {
USD amount1 = new USD(100);
EUR amount2 = new EUR(200);
EUR amount3 = new EUR(300);
 
// compile error
// amount1.add(amount2);
 
List<EUR> list = new ArrayList<EUR>();
list.add(amount2);
list.add(amount3);
 
System.out.println(sum(list).amount());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.