Opaque types in Gleam are custom types where only the module that defines the type can construct or pattern match values of the type. This is useful for creating types that should only be used in a specific way.
Opaque types are defined using the opaque keyword.
pub opaque type PositiveInt {
PositiveInt(inner: Int)
}
This PositiveInt type is to be used in situations where an int is wanted, but it has to be zero or greater. A regular Gleam Int could not be used as they can also be negative.
The module that defines this type can define a function to get the inner int value, and a function for creating the PositiveInt type which will return an error if the value is not positive.
pub fn from_int(i: Int) -> Result(PositiveInt, String) {
case i {
_ if i < 0 -> Error("Value must be positive")
_ -> Ok(PositiveInt(i))
}
}
pub fn to_int(i: PositiveInt) -> Int {
i.inner
}
With this API other modules cannot construct a PositiveInt with a negative value, so any function that takes a PositiveInt can be sure that the value is positive.
Sharp eyed students will have noticed that the TreasureChest type in the previous exercise wasn't that secure!
If you used the get_treasure function you had to supply the password, but you could still destructure the TreasureChest type to get the treasure without having to know the password.
Let's fix that by using an Opaque Type.
TreasureChest opaque type.The TreasureChest contains two fields:
String.The TreasureChest type must be opaque.
create function.This function takes two arguments:
String.The function returns a TreasureChest containing the password and the value.
If the password is shorter than 8 characters then the function should return an error saying Password must be at least 8 characters long.
open function.This function takes two arguments:
TreasureChest.String.If the password matches the password in the TreasureChest then the function should return the treasure, otherwise it should return an error saying Incorrect password.
Sign up to Exercism to learn and master Gleam with 36 concepts, 125 exercises, and real human mentoring, all for free.