Last active
July 23, 2018 14:32
-
-
Save cyriux/380275d133fa69cecf9023cb478ca36a to your computer and use it in GitHub Desktop.
Simplest monoid ever: a weight (in kg) with addition, equality and toString
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
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