Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 592
Greg Avatar asked Mar 11 '13 19:03

Greg


People also ask

What does extends app do in Scala?

trait App extends DelayedInitNo explicit main method is needed. Instead, the whole class body becomes the “main method”. args returns the current command line arguments as an array.

Can object extend trait Scala?

Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.

What is App trait in Scala?

App is a trait which is utilized to rapidly change objects into feasible programs, which is carried out by applying DelayedInit function and the objects inheriting the trait App uses this function to execute the entire body of the program as a section of an inherited main method.

What is the use of APP in Scala?

Scala provides a helper class, called App, that provides the main method. Instead of writing your own main method, classes can extend the App class to produce concise and executable applications in Scala.


1 Answers

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)
like image 131
om-nom-nom Avatar answered Nov 11 '22 11:11

om-nom-nom