Maxm007
Maxm007

Reputation: 1200

How can I use Scala reflection to find the self type traits?

trait Bar
trait Dar

trait Foo {  self : Bar with Dar =>

}

trait Child extends Foo

How do I use the new reflection API to go from typeOf[Foo] or typeOf[Child] to find out that its self type has Bar and Dar traits?

Upvotes: 1

Views: 1084

Answers (1)

ghik
ghik

Reputation: 10764

Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_10).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> :paste
// Entering paste mode (ctrl-D to finish)

trait Bar
trait Dar

trait Foo {  self : Bar with Dar =>

}

// Exiting paste mode, now interpreting.

defined trait Bar
defined trait Dar
defined trait Foo

scala> val selfTypeOfFoo = typeOf[Foo].typeSymbol.asClass.selfType
selfTypeOfFoo: reflect.runtime.universe.Type = Foo with Bar with Dar

If you want to inspect the self type further, you can match it against RefinedType:

scala> val RefinedType(parents, _) = selfTypeOfFoo
parents: List[reflect.runtime.universe.Type] = List(Foo, Bar with Dar)

scala> val RefinedType(innerParents, _) = parents(1)
innerParents: List[reflect.runtime.universe.Type] = List(Bar, Dar)

Upvotes: 1

Related Questions