Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created January 1, 2023 19:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/bd07affc984bb45372ad5a88ea0ce052 to your computer and use it in GitHub Desktop.
Save fancellu/bd07affc984bb45372ad5a88ea0ce052 to your computer and use it in GitHub Desktop.
Scala3 TypeClass example with using/given
6
123
Some(456)
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