Last active
December 27, 2020 15:18
-
-
Save deanwampler/322591b0a814054458eb8a0199c1dbe5 to your computer and use it in GitHub Desktop.
Example of using a "given Conversion" in Scala 3.
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
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: 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.net}") | |
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