Field inside object which extends App trait is set to null. Why is that so?

不羁的心 提交于 2019-12-10 12:53:03

问题


I'm trying to use scalatest to test an App like this:

object Main extends App {
    val name = "Greg"
}

class JunkTests extends FunSpec with MustMatchers {
    describe("Junk Tests") {
        it("Junk-1 -- Must do stuff") {
            println("Name: "+Main.name)
            // some test here
        }
    }
}

My name output is always null. How can I get my main object going to use its facilities during a test? In actual use I have an App that's an Http server and I want to send it messages, but right now its never initialized so the server is never started. This simple example shows that Main is never initialized.


回答1:


It should be noted that this trait is implemented using the DelayedInit functionality, which means that fields of the object will not have been initialized before the main method has been executed.

Scaladoc for App trait

So you can either:

  • define val as final: final val name = "Greg"
  • trigger main method before accessing name field
  • define name as method: def name = "Greg"
  • define name as lazy val: lazy val name = "Greg" (so in this case, as well as in previous, there is no matter in which order initialization is done)


来源:https://stackoverflow.com/questions/15346600/field-inside-object-which-extends-app-trait-is-set-to-null-why-is-that-so

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!