Haskell's newtypes in Scala

497 Views Asked by At

In Haskell we can declare newtypes to reduce dynamic memory allocations and create type-safe APIs.

newtype Username String = Username String
  deriving (Eq, Ord)

newtype works only with data types which have single constructor with single argument. Is there something similar to newtype in Scala?

Example:

case class Username(username: String)

for username we could've write something like this in Scala:

newtype Username(username: String)
1

There are 1 best solutions below

5
Jörg W Mittag On

The equivalent to Haskell's newtype are Opaque Type Aliases in Scala 3:

opaque type Username = String

It's basically a type alias … but opaque. Just like it says on the cover.