Last active
May 25, 2024 10:19
-
-
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/d1f3da63bb8aa590f6d0e36914986ee63c3b506a
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 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.4.2" | |
//> 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("[email protected]") | |
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