Skip to content
Playground(another site)

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. Choose Edit & run in-page below (or open it in the playground) to see the type-check pass, and press Run to see one string accepted and one rejected.

refined-type.bynk
context 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 && MaxLength(40)
fn greeting(subject: Subject) -> String {
"Hello, \(subject)!"
}
---
Run calls `service playground`. `Subject.of` checks each raw string, and only the
one that passes reaches `greeting`.
---
service playground {
on call() -> Effect[List[String]] by Caller {
["World", ""].map((raw) => match Subject.of(raw) {
Ok(subject) => greeting(subject)
Err(e) => "\(e.field): \(e.message)"
})
}
}