Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/b6ff54c993fb78c8f78ddff01f3d88c1 to your computer and use it in GitHub Desktop.
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/5317066627b84765adc558f1e8bc0d74e088cab
// 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.3.0"
//> 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