Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:19
Show Gist options
  • Save dacr/1fab9dd5a2c5d45f6de7fcd4123705b1 to your computer and use it in GitHub Desktop.
Save dacr/1fab9dd5a2c5d45f6de7fcd4123705b1 to your computer and use it in GitHub Desktop.
scala smart constructor / published by https://github.com/dacr/code-examples-manager #9ca3d9cf-3f2b-4bbe-aa44-83c5696859d3/fd86fb537a3fb796945cbc885617dd39a7f2eb49
// summary : scala smart constructor
// keywords : scala, adt, language-feature, smart-constructor, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 9ca3d9cf-3f2b-4bbe-aa44-83c5696859d3
// created-on : 2021-04-05T16:56:55Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
// ---------------------
// written after [John De Goes - 12 Steps To Better Scala (Part I)](https://youtu.be/71yhnTGw0hY)
// ----------------------------------------------------------------
// Smart constructor to make it impossible to define illegal state
// See also :
// - https://github.com/fthomas/refined
// - http://fthomas.github.io/talks/2016-05-04-refined
// - https://kwark.github.io/refined-in-practice/
sealed abstract case class Email private(value: String)
object Email {
def checkEmail(input:String):Boolean = {
// https://howtodoinjava.com/java/regex/java-regex-validate-email-address/
input.matches("^[a-zA-Z0-9_!#$%&’*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$")
}
def fromString(value: String):Option[Email] = {
if (checkEmail(value)) Some(new Email(value){})
else None
}
}
// The only way to create email instances...
val email = Email.fromString("john.doe@mymail.org")
email.foreach(println)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment