Tuesday 1 September 2020

Scala: Functions

‘Function’ is a block of statements used to perform a task. Once you define a function, you can call it any number of times.

Syntax

def functionName(parameters): retrunType = {

    

}

 

Example

def sum(a : Int, b : Int) : Int = {

     a + b

}

 

Above snippet define a function ‘sum’ that takes two arguments and return sum of those two arguments.
scala> def sum(a : Int, b : Int) : Int = {
     |  a + b
     | }
def sum(a: Int, b: Int): Int

scala> 

scala> sum(10, 20)
val res73: Int = 30

When you omit the return type of a function, Scala infers it automatically.

scala> def sum(a : Int, b : Int) = {
     |  a + b
     | }
def sum(a: Int, b: Int): Int

scala>

scala> def welcomeUser() = {
     |   println("Good Morning")
     | }
def welcomeUser(): Unit

In the above snippet, I omit the return type for the functions 'sum' and 'welcomeUser', Scala infer the type automatically. One thing you can observe is, welcomeUser() function does not return anything, so Scala infers the return type as Unit.

 

You can specify Unit type explicitly if you would like to.

scala> def welcomeUser() : Unit = {
     |   println("Good Morning")
     | }
def welcomeUser(): Unit

scala> 

scala> welcomeUser()
Good Morning

Note

a. Return type is not inferred for recursive functions

def fact(n : Int) = {
     if( n == 0 || n == 1){
           1
     }else{
          fact(n-1) * n
     }
}

When you try to run the above program, Scala compiler throws an error.

scala> def fact(n : Int)= {
     |   if( n == 0 || n == 1){
     |      1
     |   }else{
     |      fact(n-1) * n
     |   }
     | }
            fact(n-1) * n
            ^
On line 5: error: recursive method fact needs result type

To make the fact function work, you should specify the return type of the function.

scala> def fact(n : Int) : Int = {
     |   if( n == 0 || n == 1){
     |      1
     |   }else{
     |      fact(n-1) * n
     |   }
     | }
def fact(n: Int): Int

scala> fact(5)
val res77: Int = 120



Previous                                                    Next                                                    Home

No comments:

Post a Comment