Skip to content

Instantly share code, notes, and snippets.

@igstan
Created July 25, 2011 22:26
Show Gist options
  • Save igstan/1105403 to your computer and use it in GitHub Desktop.
Save igstan/1105403 to your computer and use it in GitHub Desktop.
Force operations on same money currencies in Java at compile time.
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