top | item 27087699

(no title)

beerbajay | 4 years ago

Scala implicits are used in a few different places, predominantly in library code where they can for example be used to derive instances of type classes. e.g. in circe:

  import io.circe.syntax._
  List(1, 2, 3).asJson
Where `asJson` requires an instance of an `Encoder`[1] and this Encoder can be derived with the help of implicits.

For you as a normal user, the two common places where you might use implicits are (1) for implicit classes providing syntactic sugar:

  // original
  def doSomething(a: A): B = ???
  val a: A = ???
  val b = doSomething(a)

  // with implicits
  implicit class AImplicits(a: A) {
    def doSomething: B = ???
  }
  val a: A = ???
  val b = a.doSomething
and for (2) implicit conversions. These are a foot-gun, so should be used in limited circumstances. At work, we use case classes in data pipelines then convert these to avro classes on save; there's lots of ways to do this, but as an example if you have an `Optional[Int]` and your avro constructor requires a nullable java `Integer` then `JavaConverters` won't save you and you'll need something like:

  implicit def optIntToInteger(optI: Option[Int]): java.lang.Integer = optI.map(Int.box).orNull
[1] https://circe.github.io/circe/api/io/circe/syntax/package$$E...

discuss

order

No comments yet.