在scala宏中推断树的类型 [英] Infer a type of a tree in a scala macro

查看:71
本文介绍了在scala宏中推断树的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在宏中,如何要求编译器推断出构造树的类型? 我只找到Context.typeCheck,但这仅检查类型,但不返回结果.

Inside a macro, how can I ask the compiler to infer the type of a constructed tree? I've only found Context.typeCheck, but that only checks the types but doesn't return the result.

推荐答案

如果对树进行了类型检查,则可以使用其tpe方法:

If you've type-checked the tree you can just use its tpe method:

scala> def impl(c: Context) = c.literal(c.typeCheck(c parse "1+1").tpe.toString)
impl: (c: scala.reflect.macros.Context)c.Expr[String]

scala> def mac = macro impl
mac: String

scala> println(mac)
Int(2)

您当然也可以将其包装在表达式中,但是如果您只想要类型,则不需要.

You could also wrap it in an expression, of course, but there's no need to if you just want the type.

这篇关于在scala宏中推断树的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆