macrame icon indicating copy to clipboard operation
macrame copied to clipboard

Delegates for generic types.

Open ClaireNeveu opened this issue 8 years ago • 1 comments

99% of the time when I want to delegate methods to a wrapped class it is for generic classes, e.g. case class WithDbMeta[A](id : Id[A], updateTime : DateTime, underlying : A). I think I've worked out a way to make @delegate work with these based on this gist and implicit macros.

The basic idea would look something like this:

// In User.scala
@delegatable
case class User(name : String, password : String)
// in WithDbMeta.scala
case class WithDbMeta[A](id : Id[A], updateTime : DateTime, @delegate underlying : A)

expanding to:

// In User.scala
case class User(name : String, password : String)
object User {
  object delegates {
    <UserLike typeclass, ops class, extension implementation, etc>
  }
}
// in WithDbMeta.scala
case class WithDbMeta[A](id : Id[A], updateTime : DateTime, @delegate underlying : A)
object WithDbMeta {
  // We would check that `T` extends some dummy trait here to perform a fast exit if this isn't delegate related. Otherwise, we try to generate the appropriate instance, using whitebox macros to fail gracefully if we have the wrong type.
  implicit def delegateInstance[T[_], A]: T[WithDbMeta[A] = macro impl
}

ClaireNeveu avatar Apr 02 '16 18:04 ClaireNeveu

The XLike type-classes should probably provide an unwrap method to get back to the underlying type.

ClaireNeveu avatar Apr 02 '16 19:04 ClaireNeveu