Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection API for Scala

Does anyone know the status of a fully-featured reflection API for Scala?

I know that you can use Java's reflection API to do simple things but this does not work well with Scala's language features. I found an interesting article describing an experimental Scala Mirroring API but as far as I know this is still experimental. I've also found mention of a ScalaSigParser but this seems to be pretty low level.

This is more of a curiosity than anything else as I am currently just playing around with Scala. I thought that the answer to this question might also be useful to others interested in Scala.

like image 445
Travis Schneeberger Avatar asked Feb 04 '10 23:02

Travis Schneeberger


People also ask

Does Scala have reflection?

Scala reflection enables a form of metaprogramming which makes it possible for programs to modify themselves at compile time. This compile-time reflection is realized in the form of macros, which provide the ability to execute methods that manipulate abstract syntax trees at compile-time.

What is reflection of API?

Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package which is essential in order to understand reflection.

What is TypeTag in Scala?

TypeTags#TypeTag . A full type descriptor of a Scala type. For example, a TypeTag[List[String]] contains all type information, in this case, of type scala. List[String] .

Where is reflection API used?

Reflection is an API which is used to examine or modify the behaviour of methods, classes, interfaces at runtime.


1 Answers

The "immutable replacement for the JavaBean style pattern" can be expressed named parameters and optionally the @BeanProperty annotation:

import reflect._
case class A(@BeanProperty val x: String, @BeanProperty val y : Int)

A(x = "s", y = 3)
A(y = 3, x = "s")

Adding methods (more precise: defining a new interface) makes only sense in a statically typed language if the client knowns about the new methods and can compile against the interface. With structural typing clients can define methods they expect to be present in an object. The Scala compiler will transform the structural type into reflection code which may fail at runtime.

type T = {def go(x : Int): Int }
def y(any : Any) = any.asInstanceOf[T].go(2)

class A{
  def go(x : Int) = x + 1
}
y(new A())
y(new {}) //this will fail

You can define new classes or traits with the interpreter on the fly. The Interpret method transforms Scala code to byte code.

You've already mentioned the ScalaSigParser which is not exactly easy to work with.

I think the rest of features you like are not there yet.

like image 114
Thomas Jung Avatar answered Nov 16 '22 04:11

Thomas Jung