Skip to content
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