Skip to content

09 · Data Structures

Validated scalar newtypes

A newtype with where makes its predicate part of construction. Its new constructor returns Result; inspect failure or propagate it. Derived operations retain validation. An ordinary newtype without where keeps its direct constructor.

On this page

A newtype with where makes its predicate part of construction. Its new constructor returns Result; inspect failure or propagate it. Derived operations retain validation. An ordinary newtype without where keeps its direct constructor.

Complete example

Validated scalar newtypes.

19-validated-newtypes.zolo
Playground
// Validation is part of construction: .new returns Result<Score, str>.

newtype Score(int) deriving Eq, Ord, Clone, Default, Add where |v| 0 <= v <= 100
newtype Positive(int) where |v| v > 0
newtype UserId(int)

let score = Score.new(40).unwrap()
let delta = Score.new(2).unwrap()
print(score.unwrap()) // expected: 40

print((score + delta).unwrap()) // expected: 42

print(score.clone() == score) // expected: true

print(Score.default().unwrap()) // expected: 0

print(Score.new(101).is_err()) // expected: true

print(Positive.new(0).is_err()) // expected: true

// Ordinary newtypes still construct directly.

print(UserId.new(7).unwrap()) // expected: 7

Rules and behavior

Validation, schemas and units · Documentation

From a checkout of the repository:

zolo examples/features/01-syntax-and-types/19-validated-newtypes.zolo

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br