Home » Scala language

Scala Composition Function

Composition function in Scala: Composition of function is the way of using multiple functions to do some work. In this tutorial on Scala composition function, we will learn about composition function with examples.
Submitted by Shivang Yadav, on September 27, 2019

Composition function in Scala

Scala composition function is a way in which functions are composed in program i.e. mixing of more than one functions to extract some results. In Scala programming language, there are multiple ways to define the composition of a function. They are,

  1. Using compose Keyword
  2. Using andthen Keyword
  3. Passing method to method

1) Scala composition function using Compose Keyword

The compose keyword in Scala is valid for methods that are defined using "val" keyword.

Syntax:

    (method1 compose method2)(parameter)

Program:

object MyObject 
{ 
	def main(args: Array[String]) 
	{ 
		println("The percentage is "+(div compose mul)(435)) 
	} 
	
	val mul=(a: Int)=> { 
		a * 100
	} 
	
	val div=(a: Int) =>{ 
		a / 500
	} 
} 

Output

The percentage is 87

2) Scala composition function using andThen Keyword

Another composition keyword that works on function defined using val keyword function is andThen.

Syntax:

    (method1 andThen method2)(parameter) 

Program:

object myObject 
{ 
	def main(args: Array[String]) 
	{ 
		println("The percentage is "+(mul andThen div)(435)) 
	} 
	
	val mul=(a: Int)=> { 
		a * 100
	} 
	
	val div=(a: Int) =>{ 
		a / 500
	} 
} 

Output

The percentage is 87

3) Scala composition function using method to method

One more way to declaring composition function in Scala is passing a method as a parameter to another method.

Syntax:

    function1(function2(parameter))

Program:

object myObject 
{ 
	def main(args: Array[String]) 
	{ 
		println("The percentage is "+ (  div(mul(456)) ))
	} 
	
	val mul=(a: Int)=> { 
		a * 100
	} 
	
	val div=(a: Int) =>{ 
		a / 500
	} 
} 

Output

The percentage is 91





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.