Generate functions at macros expansion time

2020-07-17 14:38发布

问题:

I would like to generate functions for a class accepting 1 type parameter

case class C[T] (t: T)

depending on the T type parameter.

The functions I would like to generate are derived by the functions available on T.

What I would like exactly, is to make all the functions available for T, also available for C.

As an example for C[Int], I would like to be able to call on C any function available on Int and dispatch the function call to the Int contained in C.

val c1 = new C(1)
assert(c1 + 1 == 2)

How can I achieve this by using Scala 2 or dotty macros? Or, can this be achieved in another way?

回答1:

What you're trying to do is easily achievable with implicit conversions, so you don't really need macros:

case class C[T] (t: T)

object C { //we define implicit conversion in companion object
  implicit def conversion[T](c: C[T]): T = c.t
}

import scala.language.implicitConversions
import C._

val c1 = C(1)
assert(c1 + 1 == 2) //ok

val c2 = C(false)
assert(!c2 && true) //ok

Using implicit conversions means, that whenever compiler would notice, that types don't match, it would try to implicitly convert value applying implicit function.