×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala Trait App

By IncludeHelp Last updated : October 22, 2024

Trait App

Scala uses a trait called "App" which is used to convert objects into feasible programs. This conversion is done using the DelayedInit and the objects are inheriting the trait named App will be using this function. This will convert the program code into a method that is inherited in main.

Syntax

trait App extends DelyedInit

Example of Scala Trait App

In this example, we will use the App trait to create a program that will take arguments from the command line and print the product of them.

object MyObject extends App {
  if (args.length == 1) {
    val product = args(0).toInt * 1 // Multiply the first argument by 1
    println("Product is " + product)
  } else if (args.length == 2) {
    val product = args(0).toInt * args(1).toInt // Multiply the two arguments
    println("Product is " + product)
  } else {
    println("Values not found.")
  }
}

Output

Command-line:  2 4 
Product is 8 

Here, the object with App will act as the main function and will take arguments and do the operation as required.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.