Created
January 1, 2023 19:59
-
-
Save fancellu/bd07affc984bb45372ad5a88ea0ce052 to your computer and use it in GitHub Desktop.
Scala3 TypeClass example with using/given
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
6 | |
123 | |
Some(456) |
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
object Scala3TypeClassWithUsingGiven { | |
trait MyMonoid[A] { | |
def combine(x: A, y: A): A | |
def empty: A | |
} | |
def combineList[A](li: List[A])(using monoid: MyMonoid[A]): A = li.foldLeft(monoid.empty)(monoid.combine) | |
def main(args: Array[String]): Unit = { | |
given addInts: MyMonoid[Int] with { | |
override def combine(x: Int, y: Int): Int = x + y | |
override def empty: Int = 0 | |
} | |
val sum = combineList(List(1, 2, 3)) | |
println(sum) | |
given addStrings: MyMonoid[String] with { | |
override def combine(x: String, y: String): String = x + y | |
override def empty: String = "" | |
} | |
val bigString = combineList(List("1", "2", "3")) | |
println(bigString) | |
// composing new Option[instance] from existing instance | |
given optionMonoid[T](using monoid: MyMonoid[T]) : MyMonoid[Option[T]] with { | |
override def combine(xo: Option[T], yo: Option[T]): Option[T] = for { | |
x<- xo | |
y <- yo | |
} yield monoid.combine(x,y) | |
override def empty: Option[T] = Some(monoid.empty) | |
} | |
val bigOptionString = combineList(List( | |
Option("4"), | |
Option("5"), | |
Option("6") | |
)) | |
println(bigOptionString) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment