Scala Search for reflection?

As a little thoughtful exercise, I wonder if it is possible to make a scala trait that does a deep search in the current object for other elements that meet this definition and call them. For instance:

trait CanDebug { this => def depthFirstDebug(level:Int) { for ( x<-(this object search matching type CanDebug)) { x.depthFirstDebug(level+1) } println("level "+level+" "+this.toString) } } case class A (s:String) extends CanDebug class B extends CanDebug { val a1 = A("Hello") //automatically located by CanDebug by it type val a2 = A("World") override def toString = "Start" } val b =new B b.depthFirstDebug(0) 

Put something into action:

Level 1 Hello World Level 1
Level 0 Start

Using scala 2.10.2, and I believe that this should be possible using reflection, but I'm not sure about the logistics. thank you

+4
source share
1 answer

You can use Mirrors to reflect on this , and then call the required method:

 import scala.reflect.runtime.universe._ import scala.reflect.runtime.currentMirror def depthFirstDebug(level:Int) { val mirror = currentMirror.reflect(this) val tpe = mirror.symbol.typeSignature for { m <- tpe.members if m.typeSignature <:< typeOf[CanDebug] if m.isTerm if !m.isMethod } { val fld = mirror.reflectField(m.asTerm) fld.get.asInstanceOf[CanDebug].depthFirstDebug(level + 1) } println("level "+level+" "+this.toString) } 

Now you can:

 val b =new B b.depthFirstDebug(0) 

What gives you:

 level 1 A(World) level 1 A(Hello) level 0 Start 
+3
source

Source: https://habr.com/ru/post/1497173/


All Articles