Skip to main content

Newtype

Import

import refined4s.*

Define Newtype

type NewtypeName = NewtypeName.Type
object NewtypeName extends Newtype[ActualType]

e.g.)

type Name = Name.Type
object Name extends Newtype[String]

Create Value

val newtypeName = NewtypeName(value)

e.g.)

val name = Name("Kevin")
// name: Type = "Kevin"

Get Actual Value

To get the actual value you can simply use the value method.

newtypeName.value

e.g.)

name.value
// res0: String = "Kevin"

Pattern Matching

For pattern matching, Newtype has built-in unapply so you can simply do

name match {
case Name(value) =>
println(s"Pattern matched value: $value")
}
// Pattern matched value: Kevin

Example

import refined4s.*

type Name = Name.Type
object Name extends Newtype[String]

type Email = Email.Type
object Email extends Newtype[String]

def hello(name: Name): Unit = println(s"Hello ${name.value}")

def send(email: Email): Unit = println(s"Sending email to ${email.value}")

val name = Name("Kevin")
// name: Type = "Kevin"
// Name.Type = "Kevin"
name.value
// res3: String = "Kevin"

hello(name)
// Hello Kevin

val email = Email("kevin@blah.blah")
// email: Type = "kevin@blah.blah"
// Email.Type = "kevin@blah.blah"
email.value
// res5: String = "kevin@blah.blah"

send(email)
// Sending email to kevin@blah.blah
hello("Kevin")
// error:
// Found: ("Kevin" : String)
// Required: repl.MdocSession.MdocApp0.Name
// error:
// Line is indented too far to the left, or a `}` is missing
// error:
// Line is indented too far to the left, or a `}` is missing
send("kevin@blah.blah")
// error:
// Found: ("kevin@blah.blah" : String)
// Required: repl.MdocSession.MdocApp0.Email
// error:
// Line is indented too far to the left, or a `}` is missing
// error:
// Line is indented too far to the left, or a `}` is missing