The Scala API for Quantities, Units of Measure and Dimensional Analysis
Latest commit f163fd8 Feb 24, 2017 @derekmorr derekmorr committed on GitHub Merge pull request #208 from cquiroz/parsecs
Added parsecs length unit


The Scala API for Quantities, Units of Measure and Dimensional Analysis

Squants is a framework of data types and a domain specific language (DSL) for representing Quantities, their Units of Measure, and their Dimensional relationships. The API supports typesafe dimensional analysis, improved domain models and more. All types are immutable and thread-safe.

Website | GitHub | Wiki | Join the chat at

Current Versions

Current Release: 1.2.0 (API Docs)

Development Build: 1.3.0-SNAPSHOT (API Docs)

Release History

Build Status

Build services provided by Travis CI

NOTE - This README reflects the feature set in the branch it can be found. For more information on feature availability of a specific version see the Release History or the README for a that version


Repository hosting for Squants is provided by Sonatype. To use Squants in your SBT project add the following dependency to your build.

"org.typelevel"  %% "squants"  % "1.2.0"


"org.typelevel"  %% "squants"  % "1.3.0-SNAPSHOT"

To use Squants in your Maven project add the following dependency


Beginning with Squants 0.4.x series, both Scala 2.10 and 2.11 builds are available. Beginning with Squants 1.x series, Scala 2.10, 2.11 and 2.12 builds are available.

To use Squants interactively in the Scala REPL, clone the git repo and run sbt squantsJVM/console

git clone
cd squants
sbt squantsJVM/console

Third-party integration

If you are using the PureConfig library, there is integration with Squants via pureconfig-squants. This lets you parse dimensional values out of HOCON configuration files. For example:

  far: 42.195 km
  hot: 56.7° C

Type Safe Dimensional Analysis

The Trouble with Doubles

When building programs that perform dimensional analysis, developers are quick to declare quantities using a basic numeric type, usually Double. While this may be satisfactory in some situations, it can often lead to semantic and other logic issues.

For example, when using a Double to describe quantities of Energy (kWh) and Power (kW), it is possible to compile a program that adds these two values together. This is not appropriate as kW and kWh measure quantities of two different dimensions. The unit kWh is used to measure an amount of Energy used or produced. The unit kW is used to measure Power/Load, the rate at which Energy is being used or produced, that is, Power is the first time derivative of Energy.

Power = Energy / Time

Consider the following code:

scala> val loadKw = 1.2
loadKw: Double = 1.2

scala> val energyMwh = 24.2
energyMwh: Double = 24.2

scala> val sumKw = loadKw + energyMwh
sumKw: Double = 25.4

This example not only adds quantities of different dimensions (Power vs Energy), it also fails to convert the scales implied in the val names (Mega vs Kilo). Because this code compiles, detection of these errors is pushed further into the development cycle.

Dimensional Type Safety

Only quantities with the same dimensions may be compared, equated, added, or subtracted.

Squants helps prevent errors like these by type checking operations at compile time and automatically applying scale and type conversions at run-time. For example:

scala> import{Kilowatts, Megawatts, Power}
import{Kilowatts, Megawatts, Power}

scala> val load1: Power = Kilowatts(12)
load1: = 12.0 kW

scala> val load2: Power = Megawatts(0.023)
load2: = 0.023 MW

scala> val sum = load1 + load2
sum: = 35.0 kW

scala> sum == Kilowatts(35)
res0: Boolean = true

scala> sum == Megawatts(0.035) // comparisions automatically convert scale
res1: Boolean = true

The above sample works because Kilowatts and Megawatts are both units of Power. Only the scale is different and the library applies an appropriate conversion. Also, notice that keeping track of the scale within the value name is no longer needed:

scala> import{Energy, Power, Kilowatts, KilowattHours}
import{Energy, Power, Kilowatts, KilowattHours}

scala> val load: Power = Kilowatts(1.2)
load: = 1.2 kW

scala> val energy: Energy = KilowattHours(23.0)
energy: = 23.0 kWh

Invalid operations, like adding power and energy, no longer compile:

scala> val sum = load + energy
<console>:16: error: type mismatch;
 found   :
       val sum = load + energy

By using stronger types, we catch the error earlier in the development cycle, preventing the error made when using Double in the example above.

Dimensionally Correct Type Conversions

One may take quantities with different dimensions, and multiply or divide them.

Dimensionally correct type conversions are a key feature of Squants. Conversions are implemented by defining relationships between Quantity types using the * and / operators.

Code samples in this section assume these imports:

import{Kilowatts, Power}
import squants.time.{Hours, Days}

The following code demonstrates creating ratio between two quantities of the same dimension, resulting in a dimensionless value:

scala> val ratio = Days(1) / Hours(3)
ratio: Double = 8.0

This code demonstrates use of the Power.* method that takes a Time and returns an Energy:

scala> val load = Kilowatts(1.2)
load: = 1.2 kW

scala> val time = Hours(2)
time: squants.time.Time = 2.0 h

scala> val energyUsed = load * time
energyUsed: = 2400.0 Wh

This code demonstrates use of the Energy./ method that takes a Time and returns a Power:

scala> val aveLoad: Power = energyUsed / time
aveLoad: = 1200.0 W

Unit Conversions

Code samples in this section assume these imports:

import scala.language.postfixOps
import{Gigawatts, Kilowatts, Power, Megawatts}
import squants.mass.MassConversions._
import squants.mass.{Kilograms, Pounds}
import squants.thermal.TemperatureConversions._
import squants.thermal.Fahrenheit

Quantity values are based in the units used to create them.

scala> val loadA: Power = Kilowatts(1200)
loadA: = 1200.0 kW

scala> val loadB: Power = Megawatts(1200)
loadB: = 1200.0 MW

Since Squants properly equates values of a like dimension, regardless of the unit, there is usually no reason to explicitly convert from one to the other. This is especially true if the user code is primarily performing dimensional analysis.

However, there are times when you may need to set a Quantity value to a specific unit (eg, for proper JSON encoding).

When necessary, a quantity can be converted to another unit using the in method.

scala> val loadA = Kilowatts(1200)
loadA: = 1200.0 kW

scala> val loadB = loadA in Megawatts
loadB: = 1.2 MW

scala> val loadC = loadA in Gigawatts
loadC: = 0.0012 GW

Sometimes you need to get the numeric value of the quantity in a specific unit (eg, for submission to an external service that requires a numeric in a specified unit or to perform analysis beyond Squant's domain)

When necessary, the value can be extracted in the desired unit with the to method.

scala> val load: Power = Kilowatts(1200)
load: = 1200.0 kW

scala> val kw: Double = load to Kilowatts
kw: Double = 1200.0

scala> val mw: Double = load to Megawatts
mw: Double = 1.2

scala> val gw: Double = load to Gigawatts
gw: Double = 0.0012

Most types include methods with convenient aliases for the to methods.

scala> val kw: Double = load toKilowatts
kw: Double = 1200.0

scala> val mw: Double = load toMegawatts
mw: Double = 1.2

scala> val gw: Double = load toGigawatts
gw: Double = 0.0012

NOTE - It is important to use the to method for extracting the numeric value, as this ensures you will be getting the numeric value for the desired unit. Quantity.value should not be accessed directly. To prevent improper usage, direct access to the Quantity.value field may be deprecated in a future version.

Creating strings formatted in the desired unit:

scala> val kw: String = load toString Kilowatts
kw: String = 1200.0 kW

scala> val mw: String = load toString Megawatts
mw: String = 1.2 MW

scala> val gw: String = load toString Gigawatts
gw: String = 0.0012 GW

Creating Tuple2[Double, String] that includes a numeric value and unit symbol:

scala> val load: Power = Kilowatts(1200)
load: = 1200.0 kW

scala> val kw = load toTuple
kw: (Double, String) = (1200.0,kW)

scala> val mw = load toTuple Megawatts
mw: (Double, String) = (1.2,MW)

scala> val gw = load toTuple Gigawatts
gw: (Double, String) = (0.0012,GW)

This can be useful for passing properly scaled quantities to other processes that do not use Squants, or require use of more basic types (Double, String)

Simple console based conversions (using DSL described below)

scala> 1.kilograms to Pounds
res0: Double = 2.2046226218487757

scala> kilogram / pound
res1: Double = 2.2046226218487757

scala> 2.1.pounds to Kilograms
res2: Double = 0.952543977

scala> 2.1.pounds / kilogram
res3: Double = 0.9525439770000002

scala> 100.C to Fahrenheit
res4: Double = 212.0

Mapping over Quantity values

Apply a Double => Double operation to the underlying value of a quantity, while preserving its type and unit.

scala> import

scala> val load = Kilowatts(2.0)
load: = 2.0 kW

scala> val newLoad = => v * 2 + 10)
newLoad: = 14.0 kW

The method effectively expands to q.unit(f(


Create an implicit Quantity value to be used as a tolerance in approximations. Then use the approx method (or =~, ~=, operators) like you would use the equals method (== operator).

scala> import{Kilowatts, Watts}
import{Kilowatts, Watts}

scala> val load = Kilowatts(2.0)
load: = 2.0 kW

scala> val reading = Kilowatts(1.9999)
reading: = 1.9999 kW

Calls to approx (and its symbolic aliases) use an implicit tolerance:

scala> implicit val tolerance = Watts(.1)
tolerance: = 0.1 W

scala> load =~ reading
res0: Boolean = true

scala> load ≈ reading
res1: Boolean = true

scala> load approx reading
res2: Boolean = true

The =~ and are the preferred operators as they have the correct precedence for equality operations. The ~= is provided for those who wish to use a more natural looking approx operator using standard characters. However, because of its lower precedence, user code may require parenthesis around these comparisons.


All Quantity types in Squants represent the scalar value of a quantity. That is, there is no direction information encoded in any of the Quantity types. This is true even for Quantities which are normally vector quantities (ie. Velocity, Acceleration, etc).

Vector quantities in Squants are implemented as case classes that takes a variable parameter list of like quantities representing a set of point coordinates in Cartesian space. The SVector object is a factory for creating DoubleVectors and QuantityVectors. The dimensionality of the vector is determined by the number of arguments. Most basic vector operations are currently supported (addition, subtraction, scaling, cross and dot products)

scala> import squants.{QuantityVector, SVector}
import squants.{QuantityVector, SVector}

scala> import{Kilometers, Length}
import{Kilometers, Length}

scala> import

scala> val vector: QuantityVector[Length] = SVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3))
vector: squants.QuantityVector[] = QuantityVector(WrappedArray(1.2 km, 4.3 km, 2.3 km))

scala> val magnitude: Length = vector.magnitude        // returns the scalar value of the vector
magnitude: = 5.021951811795888 km

scala> val normalized = vector.normalize(Kilometers)   // returns a corresponding vector scaled to 1 of the given unit
normalized: vector.SVectorType = QuantityVector(ArrayBuffer(0.2389509188800581 km, 0.8562407926535415 km, 0.45798926118677796 km))

scala> val vector2: QuantityVector[Length] = SVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3))
vector2: squants.QuantityVector[] = QuantityVector(WrappedArray(1.2 km, 4.3 km, 2.3 km))

scala> val vectorSum = vector + vector2        // returns the sum of two vectors
vectorSum: vector.SVectorType = QuantityVector(ArrayBuffer(2.4 km, 8.6 km, 4.6 km))

scala> val vectorDiff = vector - vector2       // return the difference of two vectors
vectorDiff: vector.SVectorType = QuantityVector(ArrayBuffer(0.0 km, 0.0 km, 0.0 km))

scala> val vectorScaled = vector * 5           // returns vector scaled 5 times
vectorScaled: vector.SVectorType = QuantityVector(ArrayBuffer(6.0 km, 21.5 km, 11.5 km))

scala> val vectorReduced = vector / 5          // returns vector reduced 5 time
vectorReduced: vector.SVectorType = QuantityVector(ArrayBuffer(0.24 km, 0.86 km, 0.45999999999999996 km))

scala> val vectorDouble = vector / 5.meters    // returns vector reduced and converted to DoubleVector
vectorDouble: squants.DoubleVector = DoubleVector(ArrayBuffer(240.0, 860.0, 459.99999999999994))

scala> val dotProduct = vector * vectorDouble  // returns the Dot Product of vector and vectorDouble
dotProduct: = 5044.0 km

scala> val crossProduct = vector crossProduct vectorDouble  // currently only supported for 3-dimensional vectors
crossProduct: vector.SVectorType = QuantityVector(WrappedArray(0.0 km, 1.1368683772161603E-13 km, 0.0 km))

Simple non-quantity (Double based) vectors are also supported.

import squants.DoubleVector

val vector: DoubleVector = SVector(1.2, 4.3, 2.3, 5.4)   // a Four-dimensional vector

Dimensional conversions within Vector operations.

Currently dimensional conversions are supported by using the slightly verbose, but flexible map method.

scala> import squants.{DoubleVector, QuantityVector}
import squants.{DoubleVector, QuantityVector}

scala> import squants.motion.Velocity
import squants.motion.Velocity

scala> import{Area, Kilometers, Length, Meters}
import{Area, Kilometers, Length, Meters}

scala> import squants.time.Seconds
import squants.time.Seconds

scala> val vectorLength = QuantityVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3))
vectorLength: squants.QuantityVector[] = QuantityVector(WrappedArray(1.2 km, 4.3 km, 2.3 km))

scala> val vectorArea =[Area](_ * Kilometers(2))      // QuantityVector(2.4 km², 8.6 km², 4.6 km²)
vectorArea: squants.QuantityVector[] = QuantityVector(ArrayBuffer(2.4 km², 8.6 km², 4.6 km²))

scala> val vectorVelocity =[Velocity](_ / Seconds(1)) // QuantityVector(1200.0 m/s, 4300.0 m/s, 2300.0 m/s)
vectorVelocity: squants.QuantityVector[squants.motion.Velocity] = QuantityVector(ArrayBuffer(1200.0 m/s, 4300.0 m/s, 2300.0 m/s))

scala> val vectorDouble = DoubleVector(1.2, 4.3, 2.3)
vectorDouble: squants.DoubleVector = DoubleVector(WrappedArray(1.2, 4.3, 2.3))

scala> val vectorLength =[Length](Kilometers(_))      // QuantityVector(1.2 km, 4.3 km, 2.3 km)
vectorLength: squants.QuantityVector[] = QuantityVector(ArrayBuffer(1.2 km, 4.3 km, 2.3 km))

Convert QuantityVectors to specific units using the to or in method - much like Quantities.

scala> val vectorLength = QuantityVector(Kilometers(1.2), Kilometers(4.3), Kilometers(2.3))
vectorLength: squants.QuantityVector[] = QuantityVector(WrappedArray(1.2 km, 4.3 km, 2.3 km))

scala> val vectorMetersNum =   // DoubleVector(1200.0, 4300.0, 2300.0)
vectorMetersNum: squants.DoubleVector = DoubleVector(ArrayBuffer(1200.0, 4300.0, 2300.0))

scala> val vectorMeters =      // QuantityVector(1200.0 m, 4300.0 m, 2300.0 m)
vectorMeters: squants.QuantityVector[] = QuantityVector(ArrayBuffer(1200.0 m, 4300.0 m, 2300.0 m))

Market Package

Market Types are similar but not quite the same as other quantities in the library. The primary type, Money, is a Dimensional Quantity, and its Units of Measure are Currencies. However, because the conversion multipliers between currency units can not be predefined, many of the behaviors have been overridden and augmented to realize correct behavior.


A Quantity of purchasing power measured in Currency units. Like other quantities, the Unit of Measures are used to create Money values.

scala> import{BTC, JPY, USD, XAU}
import{BTC, JPY, USD, XAU}

scala> val tenBucks = USD(10)      // Money: 10 USD
tenBucks: = 10.00 USD

scala> val someYen = JPY(1200)     // Money: 1200 JPY
someYen: = 1200 JPY

scala> val goldStash = XAU(50)     // Money: 50 XAU
goldStash: = 50.0000 XAU

scala> val digitalCache = BTC(50)  // Money: 50 BTC
digitalCache: = 50.000000000000000 BTC


A Ratio between Money and another Quantity. A Price value is typed on a Quantity and can be denominated in any defined Currency.

Price = Money / Quantity

Assuming these imports:

import squants.{Dozen, Each}

You can compute the following:

scala> val threeForADollar = USD(1) / Each(3)
threeForADollar:[squants.Dimensionless] = 1.00 USD/3.0 ea

scala> val energyPrice = USD(102.20) / MegawattHours(1)
energyPrice:[] = 102.20 USD/1.0 MWh

scala> val milkPrice = USD(4) / UsGallons(1)
milkPrice:[] = 4.00 USD/1.0 gal

scala> val costForABunch = threeForADollar * Dozen(10)
costForABunch: = 40.00 USD

scala> val energyCost = energyPrice * MegawattHours(4)
energyCost: = 408.80 USD

scala> val milkQuota = USD(20) / milkPrice
milkQuota: = 5.0 gal

FX Support

Currency Exchange Rates are used to define the conversion factors between currencies

scala> import{CurrencyExchangeRate, JPY, Money, USD}
import{CurrencyExchangeRate, JPY, Money, USD}

scala> // create an exchange rate
     | val rate1 = CurrencyExchangeRate(USD(1), JPY(100))
rate1: = USD/JPY 100.0

scala> // OR
     | val rate2 = USD / JPY(100)
rate2: = USD/JPY 100.0

scala> // OR
     | val rate3 = JPY(100) -> USD(1)
rate3: = USD/JPY 100.0

scala> // OR
     | val rate4 = JPY(100) toThe USD(1)
rate4: = USD/JPY 100.0

scala> val someYen: Money = JPY(350)
someYen: = 350 JPY

scala> val someBucks: Money = USD(23.50)
someBucks: = 23.50 USD

Use the convert method which automatically converts the money to the 'other' currency:

scala> val dollarAmount: Money = rate1.convert(someYen)
dollarAmount: = 3.50 USD

scala> val yenAmount: Money = rate1.convert(someBucks)
yenAmount: = 2350 JPY

Or just use the * operator in either direction (money * rate, or rate * money):

scala> val dollarAmount2: Money = rate1 * someYen
dollarAmount2: = 3.50 USD

scala> val yenAmount2: Money = someBucks * rate1
yenAmount2: = 2350 JPY

Money Context

A MoneyContext can be implicitly declared to define default settings and applicable exchange rates within its scope. This allows your application to work with a default currency based on an application configuration or other dynamic source. It also provides support for updating exchange rates and using those rates for automatic conversions between currencies. The technique and frequency chosen for exchange rate updates is completely in control of the application.

Assuming these imports:

import{CAD, JPY, MXN, USD}

You can compute:

scala> val exchangeRates = List(USD / CAD(1.05), USD / MXN(12.50), USD / JPY(100))
exchangeRates: List[] = List(USD/CAD 1.05, USD/MXN 12.5, USD/JPY 100.0)

scala> implicit val moneyContext = defaultMoneyContext withExchangeRates exchangeRates
moneyContext: = MoneyContext($@6a832973,Set($@6a832973,$@4a472c9d,$@7c65ef69,$@14ec4969,$@dbd23b8,$@3065d747,$@5260752b,$@2647f2cd,$@39fc5260,$@2ff0a2ba,$@74449a76,$@1a928eea,$@5a30090d,$@c451d07,$@5dddf889,$@44b8324a,$@6224d04d,$@2adfefc9,$@250bd9bb,$@28684af6,$@5ef09bc1,$@14756a61,$@2ae9422e,$...

scala> val energyPrice = USD(102.20) / MegawattHours(1)
energyPrice:[] = 102.20 USD/1.0 MWh

scala> val someMoney = Money(350) // 350 in the default Cur
someMoney: = 350.00 USD

scala> val usdMoney: Money = someMoney in USD
usdMoney: = 350.00 USD

scala> val usdBigDecimal: BigDecimal = someMoney to USD
usdBigDecimal: BigDecimal = 350.0

scala> val yenCost: Money = (energyPrice * MegawattHours(5)) in JPY
yenCost: = 51100 JPY

scala> val northAmericanSales: Money = (CAD(275) + USD(350) + MXN(290)) in USD
northAmericanSales: = 635.10 USD

Quantity Ranges

Used to represent a range of Quantity values between an upper and lower bound

scala> import squants.QuantityRange
import squants.QuantityRange

scala> import{Kilowatts, Power}
import{Kilowatts, Power}

scala> val load1: Power = Kilowatts(1000)
load1: = 1000.0 kW

scala> val load2: Power = Kilowatts(5000)
load2: = 5000.0 kW

scala> val range: QuantityRange[Power] = QuantityRange(load1, load2)
range: squants.QuantityRange[] = QuantityRange(1000.0 kW,5000.0 kW)

Use multiplication and division to create a Seq of ranges from the original

// Create a Seq of 10 sequential ranges starting with the original and each the same size as the original
val rs1 = range * 10
// Create a Seq of 10 sequential ranges each 1/10th of the original size
val rs2 = range / 10
// Create a Seq of 10 sequential ranges each with a size of 400 kilowatts
val rs3 = range / Kilowatts(400)

Apply foreach, map and foldLeft/foldRight directly to QuantityRanges with a divisor

// foreach over each of the 400 kilometer ranges within the range
range.foreach(Kilometers(400)) {r => ???}
// map over each of 10 even parts of the range {r => ???}
// fold over each 10 even parts of the range
range.foldLeft(10)(0) {(z, r) => ???}

NOTE - Because these implementations of foreach, map and fold* take a parameter (the divisor), these methods are not directly compatible with Scala's for comprehensions. To use in a for comprehension, apply the * or / operators as described above to create a Seq from the Range.

for {
    interval <- (0.seconds to 1.seconds) * 60  // 60 time ranges, 0s to 1s, 1s to 2s, ...., 59s to 60s
} yield ...

Natural Language DSL

Implicit conversions give the DSL some features that allows user code to express quantities in a more naturally expressive and readable way.

Code samples in this section assume these imports

import{Kilowatts, MegawattHours, Power}
import{Price, USD}
import squants.time.Hours

Create Quantities using Unit Of Measure Factory objects (no implicits required):

scala> val load = Kilowatts(100)
load: = 100.0 kW

scala> val time = Hours(3.75)
time: squants.time.Time = 3.75 h

scala> val money = USD(112.50)
money: = 112.50 USD

scala> val price = Price(money, MegawattHours(1))
price:[] = 112.50 USD/1.0 MWh

Create Quantities using Unit of Measure names and/or symbols (uses implicits):

import scala.language.postfixOps
import squants.information.InformationConversions._
import squants.time.TimeConversions._
scala> val load1 = 100 kW                   // Simple expressions don’t need dots
load1: = 100.0 kW

scala> val load2 = 100 megawatts
load2: = 100.0 MW

scala> val time = 3.hours + 45.minutes     // Compound expressions may need dots
time: squants.time.Time = 3.75 h

Create Quantities using operations between other Quantities:

scala> val energyUsed = 100.kilowatts * (3.hours + 45.minutes)
energyUsed: = 375000.0 Wh

scala> val price = 112.50.USD / 1.megawattHours
price:[] = 112.50 USD/1.0 MWh

scala> val speed = 55.miles / 1.hours
speed: squants.motion.Velocity = 24.587249174399997 m/s

Create Quantities using formatted Strings:

scala> val load = Power("40 MW")
load: scala.util.Try[] = Success(40.0 MW)

Create Quantities using Tuples:

scala> val load = Power((40.5, "MW"))
load: scala.util.Try[] = Success(40.5 MW)

Use single unit values to simplify expressions:

scala> // Hours(1) == 1.hours == hour
     | val ramp = 100.kilowatts / hour
ramp: = 100000.0 W/h

scala> val speed = 100.kilometers / hour
speed: squants.motion.Velocity = 27.77777777777778 m/s

scala> // MegawattHours(1) == 1.megawattHours == megawattHour == MWh
     | val hi = 100.dollars / MWh
hi:[] = 100.00 USD/1.0 MWh

scala> val low = 40.dollars / megawattHour
low:[] = 40.00 USD/1.0 MWh

Implicit conversion support for using Double on the left side of multiplication:

scala> val load = 10 * 4.MW
load: = 40.0 MW

scala> val driveArrayCapacity = 12 *
driveArrayCapacity: squants.information.Information = 7200.0 GB

Create Quantity Ranges using to or plusOrMinus (+-) operators:

val range1 = 1000.kW to 5000.kW              // 1000.kW to 5000.kW
val range2 = 5000.kW plusOrMinus 1000.kW     // 4000.kW to 6000.kW
val range2 = 5000.kW +- 1000.kW              // 4000.kW to 6000.kW

Numeric Support

Most Quantities that support implicit conversions also include an implicit Numeric object that can be imported to your code where Numeric support is required. These follow the following pattern:

scala> import squants.mass.{Grams, Kilograms}
import squants.mass.{Grams, Kilograms}

scala> import squants.mass.MassConversions.MassNumeric
import squants.mass.MassConversions.MassNumeric

scala> val sum = List(Kilograms(100), Grams(34510)).sum
sum: squants.mass.Mass = 134510.0 g

NOTE - Because a quantity can not be multiplied by a like quantity and return a like quantity, the Numeric.times operation of numeric is implemented to throw an UnsupportedOperationException for all types except Dimensionless.

The MoneyNumeric implementation is a bit different than the implementations for other quantity types in a few important ways.

  1. MoneyNumeric is a class, not an object like the others.
  2. To create a MoneyNumeric value there must be an implicit MoneyContext in scope.
  3. The MoneyContext must contain applicable exchange rates if you will be applying cross-currency Numeric ops.

The following code provides a basic example for creating a MoneyNumeric:

implicit val moneyContext = defaultMoneyContext
scala> implicit val moneyNum = new MoneyNumeric()
moneyNum: =$MoneyNumeric@17efb2c6

scala> val sum = List(USD(100), USD(10)).sum
sum: = 110.00 USD

Type Hierarchy

The type hierarchy includes the following core types: Quantity, Dimension, and UnitOfMeasure

Quantity and Dimension

A Dimension represents a type of Quantity. For example: Mass, Length, Time, etc.

A Quantity represents a dimensional value or measurement. A Quantity is a combination of a numeric value and a unit. For example: 2 lb, 10 km, 3.4 hr.

Squants has built in support for 54 quantity dimensions.

Unit of Measure

UnitOfMeasure is the scale or multiplier in which the Quantity is being measured. Squants has built in support for over 257 units of measure

For each Dimension a set of UOM objects implement a primary UOM trait typed to that Quantity. The UOM objects define the unit symbols, conversion factors, and factory methods for creating Quantities in that unit.

Quantity Implementations

The code for specific implementations include

  • A class representing the Quantity including cross-dimensional operations
  • A companion object representing the Dimension and set of available units
  • A base trait for its Units
  • A set of objects defining specific units, their symbols and conversion factors

This is an abbreviated example of how a Quantity type is constructed:

class Length(val value: Double, val unit: LengthUnit) extends Quantity[Length]  { ... }
object Length extends Dimension[Length]  { ... }
trait LengthUnit extends UnitOfMeasure[Length]  { ... }
object Meters extends LengthUnit { ... }
object Yards extends LengthUnit { ... }

The apply method of the UOM objects are implemented as factories for creating Quantity values.

val len1: Length = Meters(4.3)
val len2: Length = Yards(5)

Squants currently supports 257 units of measure

Time Derivatives

Special traits are used to establish a time derivative relationship between quantities.

For example Velocity is the 1st Time Derivative of Length (Distance), Acceleration is the 2nd Time Derivative.

class Length( ... ) extends Quantity[Length] with TimeIntegral[Velocity]
class Velocity( ... ) extends Quantity[Velocity] with TimeDerivative[Length] with TimeIntegral[Acceleration]
class Acceleration( ... ) extends Quantity[Acceleration] with TimeDerivative[Velocity]

These traits provide operations with time operands which result in correct dimensional transformations.

Using these imports:

import squants.motion.{Acceleration, Velocity}
import{Kilometers, Length}
import squants.time.{Hours, Seconds, Time}
import squants.time.TimeConversions._

You can code the following:

scala> val distance: Length = Kilometers(100)
distance: = 100.0 km

scala> val time: Time = Hours(2)
time: squants.time.Time = 2.0 h

scala> val velocity: Velocity = distance / time
velocity: squants.motion.Velocity = 13.88888888888889 m/s

scala> val acc: Acceleration = velocity / Seconds(1)
acc: squants.motion.Acceleration = 13.88888888888889 m/s²

scala> val gravity = 32.feet / second.squared
gravity: squants.Acceleration = 9.7536195072 m/

Power is the 1st Time Derivative of Energy, PowerRamp is the 2nd.

scala> val power = Kilowatts(100)
power: = 100.0 kW

scala> val time: Time = Hours(2)
time: squants.time.Time = 2.0 h

scala> val energy = power * time
energy: = 200000.0 Wh

scala> val ramp = Kilowatts(50) / Hours(1)
ramp: = 50000.0 W/h

Use Cases

Dimensional Analysis

The primary use case for Squants, as described above, is to produce code that is typesafe within domains that perform dimensional analysis.

This code samples in this section use these imports:

import{Money, Price}
import squants.mass.{Density, Mass}
import squants.mass.MassConversions._
import squants.motion.{Acceleration, Velocity, VolumeFlow}
import squants.motion.AccelerationConversions._
import squants.time.Time
import squants.time.TimeConversions._
scala> implicit val moneyContext = defaultMoneyContext
moneyContext: = MoneyContext($@6a832973,Set($@6a832973,$@4a472c9d,$@7c65ef69,$@14ec4969,$@dbd23b8,$@3065d747,$@5260752b,$@2647f2cd,$@39fc5260,$@2ff0a2ba,$@74449a76,$@1a928eea,$@5a30090d,$@c451d07,$@5dddf889,$@44b8324a,$@6224d04d,$@2adfefc9,$@250bd9bb,$@28684af6,$@5ef09bc1,$@14756a61,$@2ae9422e,$...

scala> val energyPrice: Price[Energy] = / megawattHour
energyPrice:[] = 45.25 USD/1.0 MWh

scala> val energyUsage: Energy = 345.kilowatts * 5.4.hours
energyUsage: = 1863000.0000000002 Wh

scala> val energyCost: Money = energyPrice * energyUsage
energyCost: = 84.30 USD

scala> val dodgeViper: Acceleration = 60.miles / hour / 3.9.seconds
dodgeViper: squants.motion.Acceleration = 6.877552216615386 m/s²

scala> val speedAfter5Seconds: Velocity = dodgeViper * 5.seconds
speedAfter5Seconds: squants.motion.Velocity = 34.38776108307693 m/s

scala> val timeTo100MPH: Time = 100.miles / hour / dodgeViper
timeTo100MPH: squants.time.Time = 6.499999999999999 s

scala> val density: Density = 1200.kilograms / cubicMeter
density: squants.mass.Density = 1200.0 kg/m³

scala> val volFlowRate: VolumeFlow = 10.gallons / minute
volFlowRate: squants.motion.VolumeFlow = 6.30901964E-4/s

scala> val flowTime: Time = 30.minutes
flowTime: squants.time.Time = 30.0 m

scala> val totalMassFlow: Mass = volFlowRate * flowTime * density
totalMassFlow: squants.mass.Mass = 1362.7482422399999 kg

Domain Modeling

Another excellent use case for Squants is stronger typing for fields in your domain model.

Code samples in this section use these imports:

import scala.language.postfixOps

import{Energy, Power, PowerRamp}
import squants.time.Time
import squants.time.TimeConversions._

This is OK ...

case class Generator(
  id: String,
  maxLoadKW: Double,
  rampRateKWph: Double,
  operatingCostPerMWh: Double,
  currency: String,
  maintenanceTimeHours: Double)

val gen1 = Generator("Gen1", 5000, 7500, 75.4, "USD", 1.5)
val gen2 = Generator("Gen2", 100, 250, 2944.5, "JPY", 0.5)

... but this is much better

case class Generator(
  id: String,
  maxLoad: Power,
  rampRate: PowerRamp,
  operatingCost: Price[Energy],
  maintenanceTime: Time)

val gen1 = Generator("Gen1", 5 MW, 7.5.MW/hour, 75.4.USD/MWh, 1.5 hours)
val gen2 = Generator("Gen2", 100 kW, 250 kWph, 2944.5.JPY/MWh, 30 minutes)

Anticorruption Layers

Create wrappers around external services that use basic types to represent quantities. Your application code then uses the ACL to communicate with that system thus eliminating the need to deal with type and scale conversions in multiple places throughout your application logic.

class ScadaServiceAnticorruption(val service: ScadaService) {
  // ScadaService returns meter load as Double representing Megawatts
  def getLoad: Power = Megawatts(service.getLoad(meterId))
  // ScadaService.sendTempBias requires a Double representing Fahrenheit
  def sendTempBias(temp: Temperature) =

Implement the ACL as a trait and mix in to the application's services where needed.

import{Irradiance, WattsPerSquareMeter}
import squants.thermal.{Celsius, Temperature}

trait WeatherServiceAntiCorruption {
  val service: WeatherService
  def getTemperature: Temperature = Celsius(service.getTemperature)
  def getIrradiance: Irradiance = WattsPerSquareMeter(service.getIrradiance)

Extend the pattern to provide multi-currency support

class MarketServiceAnticorruption(val service: MarketService)
     (implicit val moneyContext: = MoneyContext) {

  // MarketService.getPrice returns a Double representing $/MegawattHour
  def getPrice: Price[Energy] =
    (USD(service.getPrice) in moneyContext.defaultCurrency) / megawattHour

  // MarketService.sendBid requires a Double representing $/MegawattHour
  // and another Double representing the max amount of energy in MegawattHours
  def sendBid(bid: Price[Energy], limit: Energy) =
    service.sendBid((bid * megawattHour) to USD, limit to MegawattHours)

Build Anticorruption into Akka routers

// LoadReading message used within a Squants enabled application context
case class LoadReading(meterId: String, time: Long, load: Power)
class ScadaLoadListener(router: Router) extends Actor {
  def receive = {
   // ScadaLoadReading - from an external service - sends load as a string
   // eg, “10.3 MW”, “345 kW”
   case msg @ ScadaLoadReading(meterId, time, loadString) 
    // Parse the string and on success emit the Squants enabled event to routees
    Power(loadString) match {
      case Success(p) => router.route(LoadReading(meterId, time, p), sender())
      case Failure(e) => // react to QuantityStringParseException

... and REST API's with contracts that require basic types

trait LoadRoute extends HttpService {
  def repo: LoadRepository
  val loadRoute = {
    path("meter-reading") {
      // REST API contract requires load value and units in different fields
      // Units are string values that may be 'kW' or 'MW'
      post {
        parameters(meterId, time, loadDouble, unit) { (meterId, time, loadDouble, unit) =>
          complete {
            val load = unit match {
              case "kW" => Kilowatts(loadDouble)
              case "MW" => Megawatts(loadDouble)
            repo.saveLoad(meterId, time, load)
      } ~
      // REST API contract requires load returned as a number representing megawatts
      get {
        parameters(meterId, time) { (meterId, time) =>
          complete {
            repo.getLoad(meterId, time) to Megawatts


Code of Conduct

Squants is a Typelevel Incubator Project and, as such, supports the Typelevel Code of Conduct.


Code is offered as-is, with no implied warranty of any kind. Comments, criticisms, and/or praise are welcome, especially from scientists, engineers and the like.

Release procedure

Making a release requires permission to publish to sonatype, and a properly setup signing key:

To make a release do the following:

  • Ensure the version is not set to SNAPSHOT

  • Build the README using tut

  sbt tut
  • Publish a cross-version signed package
  sbt +publishSigned
  • Then make a release (Note: after this step the release cannot be replaced)
  sbt sonatypeRelease