Skip to content

Creating and Initializing Quantity Values

garyKeorkunian edited this page Dec 1, 2014 · 4 revisions

Squants provides a few different ways to create quantity values.

Using UOM Factories

Creating quantity values with Numeric values is as easy as using the UnitOfMeasure factory that the value represents. For example, when creating values of type Length, use the unit that is appropriate for the input value:

val m: Length = Meters(10.22)
val km: Length = Kilometers(10.22)
val ft: Length = Feet(10.22)
val mi: Length = UsMiles(10.22)

val kg: Mass = Kilograms(10.22)
val speed: Velocity = UsMilesPerHour(55)

These methods will accept any value of a type T where there has an implicit Numeric[T] in scope. In the current implementation, that value is converted to a Double for the underlying quantity value.

Parsing Quantity Strings

Quantities can also be created from appropriately formatted strings using the Quantity type factory:

Length("10.22 km")

These calls return a Try that contains the Quantity value on a successful parse. Otherwise it will fail with a QuantityStringParseException.

val s = Input(...)
val length: Length = Length(s) match {
  case Success(l) => l
  case Failure(e) => // react to failure
}

Dimensional Expression Results

Quantities can also be created from expressions on other quantities

val speedLimit: Velocity = UsMiles(55) / Hours(1)
val milkPrice: Price[Volume] = USD(4.25) / Gallons(1)
val energyUsed: Energy = Kilowatts(150) * Hours(3.5)

Implicits

Implicit conversions are available that provide a natural language DSL for defining quantities.

val length = 10 meters
val time = 4.2 hours
val speedLimit = 55.miles / hour
val milkPrice = 4.25.dollars / gallon
val energyUsed = 150.kilowatts * 3.5.hours
val weight = "50 lb" toMass  // Not yet available on all types - may be deprecated from existing types