Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of using a "given Conversion" in Scala 3.
scala> import scala.language.implicitConversions
scala> case class Dollars(amount: Double):
| override def toString = f"$$$amount%.2f"
| case class Percentage(amount: Double):
| override def toString = f"${(amount*100.0)}%.2f%%"
| case class Salary(gross: Dollars, taxes: Percentage):
| def net: Dollars = Dollars(gross.amount * (1.0 - taxes.amount))
// defined case class Dollars
// defined case class Percentage
// defined case class Salary
scala> given Conversion[Double,Dollars] = d => Dollars(d)
def given_Conversion_Double_Dollars: Conversion[Double, Dollars]
scala> given d2P as Conversion[Double,Percentage] = d => Percentage(d)
def d2P: Conversion[Double, Percentage]
scala> val salary = Salary(100_000.0, 0.20)
scala> println(s"salary: $salary. Net pay: ${}")
salary: Salary($100000.00,20.00%). Net pay: $80000.00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.