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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.