Skip to content

Instantly share code, notes, and snippets.

@adryanev
Forked from zlandorf/Distance.java
Created March 4, 2022 15:07
Show Gist options
  • Save adryanev/75613f253778bc1c974191e6c331814e to your computer and use it in GitHub Desktop.
Save adryanev/75613f253778bc1c974191e6c331814e to your computer and use it in GitHub Desktop.
public final class Distance {
private static final float METERS_TO_INCHES_RATIO = 39.3701f;
private final float meters;
private Distance(float meters) {
if (meters < 0f) {
throw new InvalidDistanceException();
}
this.meters = meters;
}
public float asMeters() {
return meters;
}
public float asInches() {
return meters * METERS_TO_INCHES_RATIO;
}
public static Distance ofMeters(float meters) {
return new Distance(meters);
}
public static Distance ofInches(float inches) {
return new Distance(inches / METERS_TO_INCHES_RATIO);
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Distance that = (Distance) o;
return Objects.equals(meters, that.meters);
}
@Override
public int hashCode() {
return Objects.hash(meters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment