How to use reflection at compile time

I have this situation:

class Column {
}

trait Table {
    lazy val columns: List[Column] = ....
}

class MyTable extends Table {
   val column1 = new Column()
   val column2 = new Column()
}

I would like to get a list of columns defined in derived classes at compile time.

I was already able to do this using reflection at runtime, but I heard that this can be problematic for Android and ProGuard. Therefore, I would like to do this at compile time, if possible.

https://groups.google.com/forum/#!topic/scala-on-android/Q0E_OMYqE0A

Here is my implementation with runtime mapping:

trait Table {
    lazy val columns: List[Column] = {
        import scala.reflect.runtime.universe._
        val rm = scala.reflect.runtime.currentMirror
        val columns = rm.classSymbol(this.getClass).toType.members.collect {
            case m: MethodSymbol if m.isGetter && m.returnType <:< typeOf[Column] => m
        }
        val espejo = rm.reflect(this)
        (for (col <- columns) yield
            espejo.reflectMethod(col).apply().asInstanceOf[Column]).toList
    }    
}
+4
source share
1 answer

Scala "def macro2 Scala 2.10 . def - , , , AST ( ) , , AST, .

: http://docs.scala-lang.org/overviews/macros/overview.html

+2

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


All Articles