Generate functions at macros expansion time

 ̄綄美尐妖づ 提交于 2019-12-06 05:13:29

问题


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.



来源:https://stackoverflow.com/questions/56914218/generate-functions-at-macros-expansion-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!