开发者

Can I generate foo_= and foo accessors from setFoo and getFoo?

I'm getting started with using Scala on Android and a lot of the accessor methods are standard JavaBeans accessors, e.g. setTitle(...) and getTitle(). It's a lot nicer to use the title_= and title methods in scala, so I can write code like:

button.title = "F开发者_运维知识库oo"

Is there any way to automatically map these from JavaBeans-style accessors, maybe using the Dynamic trait?


I think Dynamic would work, except it is not presently supported with syntactic sugar. Also, it would return AnyRef since there's no way to pass what the expected return type is.

Of course, you can simply use pimp my library to add appropriate Scala-style getters and setters.


I'm not sure this is supported on Android, but you can use @BeanProperty:

class X {
  @scala.reflect.BeanProperty
  var y:String = _
}

val x = new X()
x.setY("Test")
println(x.getY) //--> Test

There are more annotations for Bean support, e.g. @BooleanBeanProperty and @BeanInfo.


I don't think the dynamic trait will help you. I guess you need reflection to use the methods and they will not be discoverable through reflection.

I think you're best chance is to create a scala compiler plugin (see http://www.scala-lang.org/node/140 and http://www.sts.tu-harburg.de/people/mi.garcia/ScalaCompilerCorner/).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜