July 4, 2024
This is a Scala 3 port of the Scala 2 Type Classes example by Rock the JVM. For reference of the updated Implicits in Scala 3, read the reference on Given Instances.
In Scala 3, given and using replace the original implicit object and implicit, respectively. Define the implicit object with given and specify where it can be used with using.
trait Summable[T] { def sumElements(list: List[T]): T } given intSum: Summable[Int] with def sumElements(list: List[Int]) = list.sum // With braces (aka curly brackets) given stringSum: Summable[String] with { def sumElements(list: List[String]) = list.mkString("") } def processMyList[T](list: List[T])(using summable: Summable[T]): T = summable.sumElements(list)
Define the implicit object and override the trait methods.
trait Summable[T] { def sumElements(list: List[T]): T } implicit object IntSummable extends Summable[Int] { override def sumElements(list: List[Int]) = list.sum } implicit object StringSummable extends Summable[String] { override def sumElements(list: List[String]) = list.mkString("") } def processMyList[T](list: List[T])(implicit summable: Summable[T]): T = { summable.sumElements(list) }
@main def hello(): Unit = { val intSum = processMyList(List(1, 2, 3)) val stringSum = processMyList(List("A", "B", "C")) println(intSum) println(stringSum) } trait Summable[T] { def sumElements(list: List[T]): T } given intSum: Summable[Int] with def sumElements(list: List[Int]) = list.sum given stringSum: Summable[String] with def sumElements(list: List[String]) = list.mkString("") def processMyList[T](list: List[T])(using summable: Summable[T]): T = summable.sumElements(list)
6 ABC