Dimensions
Dimensions represent a quantifiable amount that can be measured in one or more units. Dimensions can include any measurable physical or abstract dimension, for example:
- Length, such as 1 mm
- Time, such as 1 day or 1 year
- Weight, such as 1 kg
- Money, such as 1 US Dollar
- Amount of computer storage space, such as 1 GB
Dimensions can reference complex combinations of dimensions. Speed can be represented by a unit that combines distance and time, such as 60 miles per hour. Acceleration can be represented as speed per time unit, such as 1 meter per second per second.
Each Gosu dimension is represented by a class that implements the interface
gw.lang.IDimension. You create custom dimensions by implementing the
IDimension interface. In your class declaration, parameterize the interface
as follows:
final class YOURCLASSNAME implements IDimension<YOURCLASSNAME, UNITNAME>
Replace YOURCLASSNAME with your class name. Replace
UNITNAME with a unit. The unit type might be a built-in numeric type like
int or BigDecimal, but could also be any arbitrary type
including custom types.
The default syntax for creating a dimension object is the standard new
operator with constructor arguments. A typical dimension class uses at least one numeric
constructor argument and optionally a unit type if the context requires the unit type. For
example, a new monetary amount object representing 3 US Dollars might require a numeric value
(3) and the unit (US Dollars):
var xx = new MonetaryAmount(3, Currency.TC_USD)
Create as many constructors as typical usage of your custom dimension type requires.
Gosu natively supports basic arithmetic functions on dimensions as part of the
IDimension interface. The Gosu parser looks for special methods for each
operator and checks the argument types to see what types of operations are supported. For
example, a Velocity dimension can define a multiply method
that takes a Time argument and returns a Length dimension.
Gosu uses this information to let you use the * operator to multiply a
Velocity and Time dimension, which generates a
Length object:
// Multiple Velocity and Time to get a Length object representing 150 miles
var distance = velocity * time
The following methods implement arithmetic on a custom dimension. The argument must be the type of the object on the right hand side of the arithmetic operator. The return type can be any type.
add– Addition using the+operatorsubtract– Subtraction using the-operatormultiply– Multiplication using the*operatordivision– Division using the/operatormodulo– Modulo (remainder after division) using the%operator
Additionally, you can support the unary negation operator (-) by
implementing the negate method, which takes no arguments.
