Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Strong Typing and Generics

Derived Types and Strong Typing in Ada

See how Ada prevents unit mix-ups with derived types, explicit conversions, subtype predicates and dimensional types, with the famous Mars Climate Orbiter failure as motivation.

In 1999 the Mars Climate Orbiter was lost because one team produced values in pound-force seconds and another expected newton seconds. Both were double in the code. Nothing in the language could object. Ada's answer is to make every meaningful quantity its own type, so that such a program simply does not compile.

This lesson shows how: derived types, explicit conversions, subtypes with predicates and the standard "dimensional" pattern. Ada code is read-only on this site; C stand-ins show the concept.

Distinct types from one declaration

ADA
type Meters  is new Float;
type Seconds is new Float;

D : Meters  := 100.0;
T : Seconds := 9.58;
X : Float   := D / T;     --  compile error: Meters / Seconds mismatch

type Meters is new Float; derives a new type from Float. It has the same representation and the same operations (+, -, *, <...), but it is a different type: you cannot add Meters to Seconds, or assign either to a plain Float, without an explicit conversion. Derived types also inherit the primitive subprograms of the parent, so Meters already has "+" and Float'Image-like attributes.

Explicit conversions

Between closely related types, you convert with the type name as a function:

ADA
Raw    : Float  := 3.5;
Length : Meters := Meters (Raw);     --  intentional
Back   : Float  := Float (Length);

Every conversion is visible in the text, so reviewers can search for them. When you convert between numeric types, the value is rounded or checked against the target's range.

Why not just use subtypes?

A subtype stays compatible with its parent, a type ... is new does not. Choose accordingly:

Goal Use
Values must not be mixed (meters, seconds, IDs) type X is new ...
Narrow a range but keep mixing allowed subtype X is ...
Just a documentation alias subtype X is Y;
ADA
type Customer_Id is new Positive;
type Order_Id    is new Positive;

Cust : Customer_Id := 17;
Ord  : Order_Id    := 17;
--  if Cust = Ord then ...    --  compile error: different types

A function that expects an Order_Id can never be called with a Customer_Id by mistake, a common source of production bugs in languages where both are plain integers.

Dimensional types

You can encode physics in the types. A small package defines the quantities and the operators between them:

ADA
type Distance is new Float;
type Duration_S is new Float;
type Speed is new Float;

function "/" (D : Distance; T : Duration_S) return Speed is
   (Speed (Float (D) / Float (T)));

Now D / T returns a Speed, and D + T still does not compile. GNAT also offers a Dimension_System aspect that checks real units (meters per second) at compile time, with no run-time cost.

Type predicates and invariants

Ada 2012 added subtype predicates, conditions that every value of a subtype must satisfy:

ADA
subtype Even is Integer with
   Dynamic_Predicate => Even mod 2 = 0;

subtype Hex_Digit is Character with
   Static_Predicate => Hex_Digit in '0' .. '9' | 'A' .. 'F';

X : Even := 7;      --  raises Assertion_Error when checks are enabled

A Static_Predicate can be used in case statements because the compiler knows the set. A Dynamic_Predicate can be any Boolean expression. Predicates are only checked when assertion checking is on (for GNAT, -gnata) and are provable in SPARK.

flowchart LR
    F["Float"] --> M["Meters<br/>(new Float)"]
    F --> S["Seconds<br/>(new Float)"]
    M -. "explicit conversion only" .-> S

Derived types share a representation but live in separate type families.

Universal literals still work

Numeric literals have no type until the context supplies one, so Length := 100.0; works with a derived type without any conversion. Only variables of different types need explicit conversion.

Stand-in: a compiler-checked unit mix-up in C

C cannot refuse double + double, but you can recover the safety by wrapping each quantity in a struct so that the compiler rejects mixing. The stand-in defines Meters and Seconds as distinct struct types and one operator that returns a Speed.

C Stand-in: distinct unit types in C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The second stand-in models a predicate with a validated constructor. Only values that satisfy the predicate can be built, the same promise Dynamic_Predicate makes.

C Stand-in: Even and Hex_Digit predicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Declaring everything as Integer and losing the benefit of strong typing.
  • Using subtypes where distinct types are needed (so IDs mix freely).
  • Wrapping every conversion in a helper that hides the type change.
  • Relying on predicates in production builds that suppress checks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does type Meters is new Float; create?

    A derived type is distinct; you need an explicit conversion to move between it and its parent.
  2. 2. How do you convert a Float F to Meters?

    Conversions use the target type name as a function.
  3. 3. Which declaration makes Customer_Id and Order_Id impossible to mix by accident?

    Two derived types are different types, so comparing or assigning them is a compile-time error.
  4. 4. What is a subtype predicate?

    Static_Predicate and Dynamic_Predicate attach conditions to a subtype.

Summary

  • type X is new Y makes a distinct type with the parent's representation and operations.
  • Explicit conversions mark every place where a type changes.
  • Use derived types for things that must not mix, subtypes for restrictions that may.
  • Predicates (and dimension systems) push more rules into the type system.

Next: Access Types and Memory