From 987fd8406d65505aedecd17e51216eb0ce393fbb Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Wed, 22 May 2019 17:32:40 -0400 Subject: Added new default methods to the Unit interface. --- src/org/unitConverter/unit/Unit.java | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'src/org/unitConverter/unit/Unit.java') diff --git a/src/org/unitConverter/unit/Unit.java b/src/org/unitConverter/unit/Unit.java index 86fc5a2..2ac107e 100755 --- a/src/org/unitConverter/unit/Unit.java +++ b/src/org/unitConverter/unit/Unit.java @@ -17,6 +17,7 @@ package org.unitConverter.unit; import java.util.Objects; +import java.util.function.DoubleUnaryOperator; import org.unitConverter.dimension.UnitDimension; @@ -28,6 +29,31 @@ import org.unitConverter.dimension.UnitDimension; * @since v0.1.0 */ public interface Unit { + /** + * Returns a unit from its base and the functions it uses to convert to and from its base. + * + *

+ * For example, to get a unit representing the degree Celsius, the following code can be used: + * + * {@code Unit.fromConversionFunctions(SI.KELVIN, tempK -> tempK - 273.15, tempC -> tempC + 273.15);} + *

+ * + * @param base + * unit's base + * @param converterFrom + * function that accepts a value expressed in the unit's base and returns that value expressed in this + * unit. + * @param converterTo + * function that accepts a value expressed in the unit and returns that value expressed in the unit's + * base. + * @return a unit that uses the provided functions to convert. + * @since 2019-05-22 + */ + public static Unit fromConversionFunctions(final BaseUnit base, final DoubleUnaryOperator converterFrom, + final DoubleUnaryOperator converterTo) { + return FunctionalUnit.valueOf(base, converterFrom, converterTo); + } + /** * Checks if a value expressed in this unit can be converted to a value expressed in {@code other} * @@ -59,6 +85,26 @@ public interface Unit { */ double convertFromBase(double value); + /** + * Converts a value expressed in this unit to a value expressed in {@code other}. + * + * @param other + * unit to convert to + * @param value + * value to convert + * @return converted value + * @since 2019-05-22 + * @throws IllegalArgumentException + * if {@code other} is incompatible for conversion with this unit (as tested by + * {@link Unit#canConvertTo}). + */ + default double convertTo(final Unit other, final double value) { + if (this.canConvertTo(other)) + return other.convertFromBase(this.convertToBase(value)); + else + throw new IllegalArgumentException(String.format("Cannot convert from %s to %s.", this, other)); + } + /** * Converts from a value expressed in this unit to a value expressed in this unit's base unit. *

-- cgit v1.2.3