Home » Scala language

Scala | Trait App

In Scala, a trait called "app" is used to convert objects into programs. In this tutorial on Trait App in Scala, we will learn about the trait app and its usage and working.
Submitted by Shivang Yadav, on March 06, 2020

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

Let's see an example to understand the topic better,

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) 
	{ 
		var product = {args(0).toInt}*1
		println("Product is "+ product) 
	} 
	else if (args.length == 2) 
	{ 
		var product = {args(0).toInt}*{args(1).toInt}
		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.