Skip to content

Instantly share code, notes, and snippets.

scala> new EmailAddress("@example.com") {}
<console>:15: error: illegal inheritance from sealed class EmailAddress
new EmailAddress(""){}
scala> class EvilEmailAddress(address: String) extends EmailAddress(address)
<console>:14: error: illegal inheritance from sealed class EmailAddress
class EvilEmailAddress(address: String) extends EmailAddress(address)
sealed abstract case class EmailAddress(emailAddress: String)
class EvilEmailAddress(address: String) extends EmailAddress(address)
EmailClient.sendEmail(from = new EvilEmailAddress("[email protected]"), to = new EvilEmailAddress("@example.com")) {
...
}
scala> EmailAddress("[email protected]").map(_.copy(emailAddress = "@example.com"))
<console>:13: error: value copy is not a member of EmailAddress
EmailAddress("[email protected]").map(_.copy(emailAddress = "@example.com"))
^
scala> EmailAddress("[email protected]").map(_.copy(emailAddress = "@example.com"))
res0: scala.util.Either[String,Either[String,EmailAddress]] = Right(Left(Invalid email address))
scala> for {
| e1 <- EmailAddress("[email protected]")
| e2 <- e1.copy(emailAddress = "@example.com")
| } yield e2
res1: scala.util.Either[String,EmailAddress] = Left(Invalid email address)
case class EmailAddress(emailAddress: String) {
def copy(emailAddress: String = emailAddress): Either[String, EmailAddress] = {
EmailAddress(emailAddress)
}
}
scala> val emailAddress = EmailAddress("[email protected]")
emailAddress: Either[String,EmailAddress] = Right(EmailAddress([email protected]))
scala> emailAddress.map(_.copy(emailAddress = "@example.com"))
res0: scala.util.Either[String,EmailAddress] = Right(EmailAddress(@example.com))