Last active
May 27, 2023 15:30
-
-
Save dacr/18db5be8c31007d733cb58b9008e0fd9 to your computer and use it in GitHub Desktop.
scala smart constructor with value classes / published by https://github.com/dacr/code-examples-manager #ed5363d3-527d-4e97-9e03-229998e4424e/b0062ab01f09b36a87d83b79d36fb11a48e43c95
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 with value classes | |
// keywords : scala, adt, language-feature, smart-constructor, value-class, @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 : ed5363d3-527d-4e97-9e03-229998e4424e | |
// created-on : 2022-06-15T20:38:16+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.3.0" | |
//> using objectWrapper | |
// --------------------- | |
// 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/ | |
class Email private(val value: String) extends AnyVal: | |
override def toString: String = value | |
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(Email(value)) | |
else None | |
} | |
} | |
// The only way to create email instances... | |
val email = Email.fromString("john.doe@mymail.org") | |
email.foreach(println) | |
// Email("truc machin") // DO NOT COMPILE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment