简体   繁体   English

Scala中符号的导入和通配符导入

[英]Imports and wildcard imports of Symbols in Scala

I have a list of Symbols representing packages, objects and classes and want to import them in a macro context. 我有一个表示包,对象和类的符号列表,并希望在宏上下文中导入它们。

For packages and objects, this would mean a wildcard import and for classes it would mean a “standard” import. 对于包和对象,这将意味着通配符导入,对于类,它将意味着“标准”导入。

Given a List[Symbol] consisting of some.package , some.Class and some.Object , how would I properly import those and how can I decide whether a “standard” or a wildcard import needs to be used? 给定一个List[Symbol]some.packagesome.Classsome.Object ,我如何正确导入它们?如何判断是否需要使用“标准”或通配符导入?

My current approach is this: 我目前的做法是:

def importPackageOrModuleOrClass(sym: Symbol): Import =
  if (sym.isPackage || sym.isModule) // e. g. import scala._, scala.Predef
    gen.mkWildcardImport(sym)
  else                               // e. g. import java.lang.String
    gen.mkImport(sym.enclosingPackage, sym.name, sym.name) // <--- ?????

The package/module import works, but the class import doesn't although it looks correct. 包/模块导入有效,但类导入虽然看起来不正确。

You need to get the "TermName" like this... 你需要得到像这样的“TermName” ......

def importPackageOrModuleOrClass(sym: Symbol): Import =
if (sym.isPackage || sym.isModule)
    gen.mkWildcardImport(sym)
else
    gen.mkImport(sym.enclosingPackage, sym.name.toTermName, sym.name.toTermName)

You can grab more hints regarding importing, reflecting, etc. via the sourcecode at http://xuwei-k.github.io/scala-compiler-sxr/scala-compiler-2.10.0/scala/reflect/internal/Importers.scala.html 您可以通过http://xuwei-k.github.io/scala-compiler-sxr/scala-compiler-2.10.0/scala/reflect/internal/Importers上的源代码获取有关导入,反映等的更多提示。 scala.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM