Scala – Functions

  • date 30th September, 2020 |
  • by Prwatech |
  • 0 Comments

Scala Function

To execute a group of statements to perform a task a hundred times, we don’t type them a multiple times. We combine them into a function, put a call to that function inside a loop, and make that loop run multiple times. it makes easier to debug and modify the lines of code. We can divide according to the tasks we carry out in our code.

Mainly two types:

1.     In built Functions

2.     User-defined Functions

Advance functions:

1.     HOF –Higher Order Function

2.     Generic Function

3.     Lambda

Here are some use cases to define Functions in Scala:-

1)

The Same Program can also be defined using Lambda Function:

It is not only specific to a particular Data Type, Here in the Eg. You can have a look how to give a standard code for any Data Type

2) Area of circle

scala> def area(radius:Int): Double = {3.14*radius*radius}

scala> area(6)

3) Factorial of a number

scala> def factorial(n:Int):Int = if(n==0) 1 else n*factorial(n-1)

scala>  factorial(8)

 

Quick Support

image image