×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala Composition Function

By IncludeHelp Last updated : October 20, 2024

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

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)

Example

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

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) 

Example

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

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))

Example

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!

Load comments ↻





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