EindbaasExpress / handsonscala-issuemigrator

Part of the HandsOnScala Course
0 stars 0 forks source link

enhancement to build ReadWriter classes by composition #66

Open EindbaasExpress opened 2 years ago

EindbaasExpress commented 2 years ago

I occasionally need to implement my own ReadWriter[X]. So far I've always been able to do this by converting to some other type that already has an instance. This requires two functions, one to map to that type and one to map back from it. This is common enough that I've made a an implicit class to add syntax.

object Helper {
  implicit class EnhancedReadWriter[A](val _rw: ReadWriter[A]) extends AnyVal {
    def compose[B](down: B => A, up: A => B): ReadWriter[B] = new ReadWriter[B](
      write = a => _rw.write(down(a)),
      read = { case (b) => up(_rw.read(b)) })
  }
}

I use it like this:

implicit val dateReadWrite: ReadWriter[Date] = (implicitly[ReadWriter[Long]]).compose(
      down = _.getTime,
      up = new Date(_) )

Is this worth adding centrally?

ID: 7 Original Author: drdozer