1

Scala 2.10 comes with a great reflection API. There are two entry points to it, however: runtime universe and macro context universe.

When using runtime reflection, you should import scala.reflect.runtime.universe. When using reflection inside a macro implementation, you should import universe from the context.

Is it possible to write some code that works in both environments? How should one obtain the universe?

Consider this example:

class MyReflection(val u: scala.reflect.api.Universe) {
  import u._

  def foo[T: TypeTag] = implicitly[TypeTag[T]].tpe.members // returns MyReflection.u.MemberScope
}
val x = new MyReflection(scala.reflect.runtime.universe)
val members: scala.reflect.runtime.universe.MemberScope = x.foo[String] // BANG! Compiler error

This won't compile because of type mismatch. Same time, it is obvious that both scala.reflect.runtime.universe.MemberScope and MyReflection.u.MemberScope in this example share the same API. Is there a way to abstract over different universes?

Or am I possibly doing something philosophically wrong with trying to export reflection artifacts (MemberScope in this example)?

1 Answer 1

2

You can just accept the universe as a parameter:

class MyReflection(val u: scala.reflect.api.Universe) {
  import u._

  def foo[T : TypeTag] = implicitly[TypeTag[T]].tpe.members
}


val x = new MyReflection(scala.reflect.runtime.universe)

Note that you'll have to refer to the universe via your instance of MyReflection to get the path-dependent types right.

val members: x.u.MemberScope = x.foo[String]

Have a look at this question for more examples and options.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your anwser! While this hint is a solution, it has a noticeable downside for me. I've updated the question with the description of it.
Welcome to the downside of path-dependent types. You have no choice but to do everything you want to do under the scope of MyReflection, or refer to MyReflection's implementation of Universe. See updated answer.
Thanks! Looks like this (see section "Writing bigger macros") will help me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.