Opaque types
Magda Stożek
Get more clarity with
The perfect model
- Precise
- Readable
- Prevents mistakes
Scala 2
- Type aliases
- Refined types
- Value classes
type Age = Int
case class Age(value: Int) extends AnyVal
type Age = Int Refined Positive
Opaque type aliases
Demo:
- why "opaque"
- how to add API
- object methods
- instance methods
- bounds
Newtypes
- zero-cost wrapper
- Scala 2
- Scala 3
- opaque types?
- Monix's Newtypes
- ZIO Prelude
- Iron
Refined types
type Pages = Int
Pages(350)
if (value > 0) Some(value) else None
Ecosystem
Opaque types + Iron
Demo
Opaque types summary
Advantages:
- simple and clear
- no overhead
- opaque
Disadvantages:
- no API (*unless bounds)
- no pattern matching
- no toString/equals overriding
Read more
- Opaque types documentation: https://docs.scala-lang.org/scala3/reference/other-new-features/opaques.html
- Demo code: https://github.com/magdzikk/opaque-types
- Discussion about newtypes in Scala: https://contributors.scala-lang.org/t/improve-opaque-types/4786
Questions?
opaque type EndOfPresentation = TimeToAskQuestions
Opaque types in Scala 3 [40 min]
By Magda Stożek
Opaque types in Scala 3 [40 min]
- 46