Last active
May 25, 2024 10:20
-
-
Save dacr/b6ff54c993fb78c8f78ddff01f3d88c1 to your computer and use it in GitHub Desktop.
value class scala feature / published by https://github.com/dacr/code-examples-manager #0dbdfc09-d86a-4943-8f0d-62d98399fea8/a4303a017a915f520f774f3829dc5723e16d1031
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 : value class scala feature | |
// keywords : scala, language-feature, performance, domain-model, @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 : 0dbdfc09-d86a-4943-8f0d-62d98399fea8 | |
// 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" | |
//> using objectWrapper | |
// --------------------- | |
import java.time.* | |
// https://dzone.com/articles/what-value-classes-is | |
println("A value class has only one parameter but can have defs") | |
println("Typically to give a type to a tiny type : UserId, UserName, CloudId, ...") | |
class UserId(val id:Int) extends AnyVal | |
println(UserId(2).id) | |
class Euros(val amount:Long) extends AnyVal: | |
override def toString: String = s"${amount}€" | |
def add(that:Euros):Euros = Euros(amount+that.amount) | |
println(Euros(20).add(Euros(22))) | |
class When(val timestamp:Long) extends AnyVal: | |
override def toString: String = Instant.ofEpochMilli(timestamp).toString | |
def f1(amount: Long, when:Long) = s"when:$when amount:${amount}€" | |
def f2(amount: Euros, when:When) = s"when:$when amount:$amount" | |
println(f1(10L, System.currentTimeMillis)) | |
println(f1(System.currentTimeMillis(), 10L)) // Easy to give the wrong parameter | |
println(f2(Euros(10), When(System.currentTimeMillis))) | |
println( | |
"""Value classes are interesting | |
| - for domain modelling and avoid using the same types everywhere (String for everything, ...) | |
| - for performance optimization and memory optimization | |
| """.stripMargin | |
) | |
println("The generated bytecode will unwrap the value class, using directly the parameter type and thus avoid overhead ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment