【发布时间】:2021-05-06 16:52:57
【问题描述】:
我正在努力获取 Scala3 宏实现中的类型信息。我会通过代码来解释问题。
这里是应用逻辑:
object BlockServiceImpl extends BlockService:
def authenticateUser0() = new ServiceCall[AuthUser,AuthUserResponse]:
def invoke(request: AuthUser): Future[AuthUserResponse] =
println("BlockServiceImpl authenticateUser0 called")
Future.successful(AuthUserResponse("test"))
现在,对于我想借助宏创建端点的逻辑。
defineRoute("POST","/v1/block",BlockServiceImpl.authenticateUser0)
这是内联方法:
inline def defineRoute[Q: RootJsonFormat ,R: RootJsonFormat](method: String, uri: String,inline call: () => ServiceCall[Q,R]): AkkaHttpCall = ${ methodImpl[Q,R]('uri, 'call)}
这是宏的实现:
def methodImpl[Q: Type,R: Type](uri: Expr[String],expr: Expr[Function0[ServiceCall[Q,R]]])(using ctx: Quotes): Expr[AkkaHttpCall] = ...
如何在编译时的宏扩展过程中获取Q 是AuthUser 类型的信息?
【问题讨论】:
-
Q: Type, R: Type你的methodImpl没有边界,你能相应地绑定它们吗? (我对新的宏不是很熟悉,但是如果类型没有边界,你怎么能强制执行某个类型呢?) -
如何绑定?
-
我认为使用上限:
Q <: AuthUser : Type. -
不同的Q类型会有不同的defineRoute调用。
-
@zlaja 如果类型层次结构定义明确,类型边界会非常有用。对于相同或子类,我们可以使用“上限”或“[T <: r>: R]”。我们可以使用“[T >: R <: w href="https://blog.knoldus.com/scala-type-bounds/" rel="nofollow" target="_blank">blog.knoldus.com/scala-type-bounds
标签: scala macros scala-macros