Last active
April 2, 2023 10:12
-
-
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/18796e10c5e16739906e04caf6e4b037244ecd4a
This file contains 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.1.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