https://github.com/samcarlberg/units
A simple Java unit library
https://github.com/samcarlberg/units
java units units-of-measure
Last synced: 3 months ago
JSON representation
A simple Java unit library
- Host: GitHub
- URL: https://github.com/samcarlberg/units
- Owner: SamCarlberg
- Created: 2017-02-07T01:47:22.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2023-05-27T04:54:06.000Z (about 2 years ago)
- Last Synced: 2025-02-13T10:18:25.770Z (5 months ago)
- Topics: java, units, units-of-measure
- Language: Java
- Size: 196 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Units
A simple Java unit library to provide compile-time safety for units. No more of this:
```java
double distance = 12.34; // What unit is this?
```Now you can have this:
```java
Measure distance = Units.Inches.of(12.34); // It has to be inches!
```And since `Inches` is a built-in unit, we can use a special subclass of `Measure`
```java
Inches distance = Inches.of(12.34);
```Note that this `Inches` class is _not_ the same thing as `Units.Inches`
Of course, units can be converted from one type to another, as long as they measure the same kind of thing!
```java
void doSomething(Measure distance) {
// Convert the distance to some known type that this class can use
double inches = distance.as(Units.Inches);
// ...
}
```## Creating custom units
This library has many common units, but sometimes you just want to use furlongs or stone:
```java
Unit Furlongs = Units.Feet.aggregate(660);
Unit Stone = Units.Pounds.aggregate(14);
Unit Milligram = Units.Grams.splitInto(1000);
```#### `aggregate(double)` and `splitInto(double)`
`unit.aggregate(n)` creates a new unit that is equivalent to _n_ of the original unit; the new unit is the "aggregate" of _n_ of the original unit
`unit.splitInto(n)` is the reverse; it creates a new unit that is equivalent to 1 / _n_ of the original unit (the original unit is "split into" _n_ equal parts, each of which is equal to 1 of the resulting unit)
For example,
```java
Unit kilo = someUnit.aggregate(1000);
Unit milli = someUnit.splitInto(1000);
```## Sample use
```java
interface Gyro {
Measure getAngle();
}Gyro gyro = ...
Measure angle = gyro.getAngle();
```Generally, if you want to declare some constant measure (such as a target angle or distance), those should be declared using the specialized measure classes, eg `Inches targetDistance = Inches.of(...)`. This makes the code much clearer since the unit is determinable just by looking at the left-hand side of the declaration.
If you're just grabbing the output of a sensor and passing that to something that consumes that kind of measure (e.g. reading a voltage from an analog sensor and passing that to a motor), then it's okay to use a generic `Measure sensorOutput = mySensor.getRawVoltage()`