Import and wildcard character import in Scala

I have a list of characters representing packages, objects, and classes, and you want to import them in a macro context.

For packages and objects, this will mean importing wildcards, and for classes, this will mean "standard" import.

Given a List[Symbol] consisting of some.package , some.Class and some.Object , how should I import them correctly and how can I decide whether to use a "standard" or wildcard?

My current approach is this:

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

The package / module is imported, but the class is not imported, although it looks correct.

+7
source share
1 answer

You need to get "TermName" like this ...

 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 get more tips regarding import, reflection, etc. through the source code http://xuwei-k.imtqy.com/scala-compiler-sxr/scala-compiler-2.10.0/scala/reflect/internal/Importers.scala.html

+1
source

All Articles