Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 285
soc Avatar asked Mar 26 '13 09:03

soc


1 Answers

You need to get the "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 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

like image 56
e-sushi Avatar answered Sep 22 '22 15:09

e-sushi