seanmcl
seanmcl

Reputation: 9944

Shapeless StringLike trait with minimal boilerplate

I'm trying to define a general method for making string-like types. For example, I'd like

case class Foo1(s: String) extends AnyVal
case class Foo2(s: String) extends AnyVal
...

to have, say scalaz.Show, scalaz.Equal, argonaut.CodecJson, etc. instances. I know this is possible using hacky methods like grabbing the apply/unapply functions generated by the case classes, but I was hoping to come up with a type-safe, boilerplate-free solution with shapeless. Here's the best I've come up with:

import scalaz._, Scalaz._
import argonaut._, Argonaut._
import shapeless._

trait HasName[A] {
  def to(v: A): String
  def fr(v: String): A
}

object HasName {
  def apply[A](implicit instance: HasName[A]): HasName[A] = instance
  def instance[A](f: A => String, g: String => A): HasName[A] = new HasName[A] { def to(v: A) = f(v); def fr(v: String) = g(v) }

  implicit val hlist: HasName[String :: HNil] = new HasName[String :: HNil] {
    def to(v: String :: HNil) = v.head
    def fr(v: String) = v :: HNil
  }

  implicit def generic[A, R](implicit F: Generic.Aux[A, R], G: HasName[R]): HasName[A] = instance(
    v => G.to(F.to(v)),
    v => F.from(G.fr(v))
  )
}

trait Name[A] {
  val F: HasName[A]
  implicit val show: Show[A] = Show.shows(F.to)
  implicit val read: Read[A] = Read.readUnsafe(F.fr)
  implicit val json: CodecJson[A] = CodecJson[A](v => jString(F.to(v)), c => c.as[String] map F.fr)
  implicit val equal: Equal[A] = Equal.equalA[A]
}

Then users can do

case class Foo1(s: String) extends AnyVal
object Foo1 extends Name[Foo1] {
  val F = cachedImplicit[HasName[Foo1]]
}

This isn't too much boilerplate, but there is still that pesky F. I tried this:

class Name[A](implicit F: HasName[A]) {
  implicit val show: Show[A] = Show.shows(F.to)
  implicit val read: Read[A] = Read.readUnsafe(F.fr)
  implicit val json: CodecJson[A] = CodecJson[A](v => jString(F.to(v)), c => c.as[String] map F.fr)
  implicit val equal: Equal[A] = Equal.equalA[A]
}

which would be nicer at the call site:

object Foo1 extends Name[Foo1]

but it doesn't work; you can't have implicit by-name parameters, and you can't pass a non-by-name circular reference.

Any ideas on how to keep both the caller and callee code nice?

Upvotes: 3

Views: 58

Answers (1)

Cyrille Corpet
Cyrille Corpet

Reputation: 5305

You could use the fact that your HasName will be implicitly in scope to do the following

trait Name[A] {
  implicit def show(implicit F: HasName[A]): Show[A] = Show.shows(F.to)
  implicit def read(implicit F: HasName[A]): Read[A] = Read.readUnsafe(F.fr)
  implicit def json(implicit F: HasName[A]): CodecJson[A] = CodecJson[A](v => jString(F.to(v)), c => c.as[String] map F.fr)
  implicit def equal(implicit F: HasName[A]): Equal[A] = Equal.equalA[A]
}

Upvotes: 1

Related Questions