neotype.Newtype
See theNewtype companion object
abstract opaque class Newtype[A] extends TypeWrapper[A]
Newtype
allows for the creation of distinct types from existing ones, enabling more type-safe code by leveraging the type system to enforce constraints at compile time.
Overriding the validate
method allows for custom validation logic to be executed at compile time, ensuring that the newtype is only created with valid input. If the validation fails, it will raise a compile-time error.
Example:
// DEFINITION
type Digits = Digits.Type
object Digits extends Newtype[String]:
override inline def validate(value: String) =
value.forall(_.isDigit)
// COMPILE-TIME VALIDATION
Digits("123") // Compiles successfully.
Digits("abc") // Would fail to compile due to validation.
// RUN-TIME VALIDATION
val input = "123"
Digits.make(input) // Right(Digits("123"))
val bad = "abc"
Digits.make(bad) // Left("String must be numeric")
Attributes
- Companion
- object
- Graph
-
- Supertypes
Members list
In this article