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(_) )
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.
I use it like this:
Is this worth adding centrally?
ID: 7 Original Author: drdozer