开发者

Do Scala objects survive activity restarts on Android?

I'm writing an Android app in Scala, and I haven't been able to find a clear answer to this question.

My application contains an object with a bunch of开发者_开发知识库 static data defined in vals. The data includes instances of classes.

My question is, what happens to my object when Android decides to kill the activity and later restarts it? I understand that objects in Scala can be used to achieve a similar purpose to static values in Java, but are not actually implemented that way in the generated bytecode. So does Android know to re-initialize my object when it restarts the activity? Are there circumstances where it would not do so, or where I have to be careful?

If the answer to the above is "all is fine", I gather that an object composed of mutable data would be quite different. In that case I'm pretty sure that I would need to explicitly save/restore such objects to retain the state. But it seems silly to have to save/restore data that is always the same and is hard-wired into the APK itself.


In short, objects are translated to singletons, and the single instance is held in a static final field. Therefore objects will be reinitialized, and you'll need serialization to restore the same data for mutable objects.

Programming in Scala (from Odersky et al.), chapter 31, explains how to use the decompiler to get the answer you need - it's very easy.

Basically, given an object like this:

object App {
 def main(args: Array[String]) {
  println("Hello, world!")
 }
}

It will be translated to a class named App$ implementing the singleton pattern. In particular, the singleton instance is contained within a field defined as public static final App$ MODULE$ = new App$(); , and the methods are defined as instance methods. javap App$ can be used to confirm the declaration of the field - probably jad can decompile also the source code. If no companion class is defined, Scala will also define a class named App containing corresponding static final methods to call from Java. This way, you get an App.main method with the right signature and can invoke scala App, which in turn invokes java App with the right additional libraries.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜