开发者

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开发者_如何学Python 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜