Field inside object which extends App trait is set

2019-06-16 20:36发布

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条回答
Summer. ? 凉城
2楼-- · 2019-06-16 21:28

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)
查看更多
登录 后发表回答