Scala | Trait App

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.
Note:

trait App extends DelayedInit
  • The Linear Super-types here are:
    DelayedInit, AnyRef, Any
  • The value members are:
    val executionStart: Long
    def main(args: Array[String]): Unit
  • Now, lets see some examples.

    • Example :



      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Scala program of a trait
      // App
        
      // Applying the trait App
      object GfG extends App
      {
        
          // Displays output
          println("GeeksforGeeks")
        
      }

      chevron_right

      
      

      Output:

      GeeksforGeeks
      

      Here, the object GfG inherits the main method of App and prints the output, and so we don’t need to create the main method manually.

    • Example:

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Scala program of trait
      // App
      object GfG extends App 
      {
          // conditions stated
          if (args.length == 1)
          {
        
              // Displays this as output if 
              // the command line arguments
              // are equal to one
              println("Student: ${args(0)}")
          }
            
          else
          {
            
              // Displays this if no arguments 
              // are given in the command line
              println("There are no students.")
          }
      }

      chevron_right

      
      

      Output:

      There are no students.
      

      Note: Here, args is utilized for command line arguments, which will return the instant command line arguments like an array.
      The output obtained here is the string stated above in the else part as no command line arguments are provided. If we provide the command line arguments like below then the output will be:

      // command line argument
      $ scala GfG Nidhi 
      
      // Output
      Student: Nidhi
      

      Here, one argument is given so only that is returned.



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.