Last active
May 25, 2024 10:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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("[email protected]") | |
email.foreach(println) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment