Scala
Type Classes (Cats-style)
Ad-hoc polymorphism via type classes.
By EZ4Code Team
type-classcatspolymorphism
Code
// Define
trait Semigroup[A] {
def combine(x: A, y: A): A
}
// Instances
implicit val intSum: Semigroup[Int] = (x, y) => x + y
implicit val strConcat: Semigroup[String] = (x, y) => x + y
// Generic function
def combineAll[A](xs: List[A])(implicit s: Semigroup[A]): A =
xs.reduce(s.combine)
combineAll(List(1, 2, 3)) // 6
combineAll(List("a", "b", "c")) // "abc"
// Cats provides Monoid, Functor, Monad, etc. the same wayExplanation
Type classes let you add behavior to types retroactively without modifying them. Define the trait, provide instances, and write generic functions. Cats is the mainstream library. This is more flexible than OOP inheritance and powers Haskell-style polymorphism in Scala.
More Scala Snippets
Pattern Matching
Destructure values and match cases in Scala.
Case Classes
Immutable data classes with auto-generated equals/hashCode/toString.
Collections Operations
Functional collection operations: map, filter, fold, groupBy.
Traits and Mixins
Compose behaviors using traits with default implementations.
Futures and Async
Asynchronous computation with Future and ExecutionContext.
Implicits (Given/Using in Scala 3)
Type-class derivation and context passing via implicits.