Scala – Functions

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

Scala | Functions - Basics

 

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.

 

In Scala, functions are fundamental constructs that encapsulate reusable blocks of code and enable modular programming. Functions in Scala are first-class citizens, meaning they can be treated like any other value, such as integers or strings. This allows functions to be passed as arguments to other functions, returned from functions, and stored in variables.

Scala supports both named functions defined with the def keyword and anonymous functions defined using function literals (=>). Function parameters in Scala are explicitly typed, but type inference often allows for concise function definitions without specifying parameter types explicitly.

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

Scala | Functions - Basics

Quick Support

image image