Scala
Implicits (Given/Using in Scala 3)
Type-class derivation and context passing via implicits.
By EZ4Code Team
implicittype-classscala3
Code
// Type class definition
trait Show[A] {
def show(a: A): String
}
// Instance
implicit val showInt: Show[Int] = (a: Int) => a.toString
// Usage (implicit parameter)
def printIt[A](a: A)(implicit s: Show[A]): Unit =
println(s.show(a))
printIt(42) // "42" — compiler finds showInt
// Scala 3 syntax:
// given Show[Int] with { def show(a: Int) = a.toString }
// def printIt[A](a: A)(using s: Show[A]): Unit = ...Explanation
Implicits (renamed to given/using in Scala 3) enable type classes, context passing, and extension methods. The compiler searches for matching instances in scope. They power libraries like Cats and Shapeless. Use them sparingly to avoid implicit ambiguity.
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.
Akka Actors (Pekko)
Message-passing concurrency with the actor model.