Skip to content

Instantly share code, notes, and snippets.

@cyriux
Last active July 23, 2018 14:32
Show Gist options
  • Save cyriux/380275d133fa69cecf9023cb478ca36a to your computer and use it in GitHub Desktop.
Save cyriux/380275d133fa69cecf9023cb478ca36a to your computer and use it in GitHub Desktop.
Simplest monoid ever: a weight (in kg) with addition, equality and toString
public class Weight {
private final double weight;
public final static Weight ZERO = new Weight(0.);
public Weight(double weight) {
if (weight < 0) {
throw new IllegalArgumentException("Weight must be positive");
}
this.weight = weight;
}
public Weight add(Weight other) {
return new Weight(weight + other.weight);
}
@Override
public int hashCode() {
return (int) (31 ^ doubleToLongBits(weight));
}
@Override
public boolean equals(Object o) {
Weight other = (Weight) o;
return doubleToLongBits(weight) == doubleToLongBits(other.weight);
}
@Override
public String toString() {
return weight + "kg";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment