Skip to content

Refined types

A refined type is an ordinary type with a predicate attached. Subject is a String, but only one that is non-empty and at most 40 characters — the constraint is part of the type, not a runtime convention you have to remember. The compiler tracks the difference between a raw String and a Subject everywhere.

The pay-off is in greeting: because its parameter is a Subject, it never validates its input. Every Subject in existence has already passed the check at the point it was constructed, so the body can simply use it. Open it in the playground to see the type-check pass.

refined-type.bynk
commons demo
---
Who we are greeting — non-empty, at most 40 characters.
A refined type: every `Subject` that exists has already passed this check,
so `greeting` never needs to validate its input.
---
type Subject = String where NonEmpty and MaxLength(40)
fn greeting(subject: Subject) -> String {
"Hello, \(subject)!"
}