FP Module 2 - 101 Scala

Bubu
7,437 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Function (basics) Next: Function Recursion

Function Definition : Several ways

As said earlier, a Scala function definition is defined such as:

def functionName ([list of parameters]) : [return type] = {
   function body
   return [expr]
}

The return keyword could (and should) be omitted when the last statement of the function is returned. The return type clause can (almost the time) be omitted because Scala will often infer it (automatic deduct the data type of an expression). You will see that in some occasion, it can't (you will see more about in the next section about function recursion).

You will see bellow that there are several ways to define a function in Scala. ** Each of the definition bellow is equals **

Function definition (common way)

def plusOne(x: Int): Int = {
   return x + 1
}

As previously said, in this case the return type can be omitted. Also, when there is only one statement, the curly brackets can be omitted:

def plusOne(x: Int) = x + 1

Anonymous function

There are some cases where you would like to get a function without naming it (for example, when you pass a function as a parameter).

(x: Int) => x +1

The function above defines a non named function that take an Integer x and return the value of x plus one.

We will look deeper at how and when to use this type of function in next course about High Order Functions.

Object function

An other way to defined a function, is that considering it as an object first-class citizen. Then, we will use the type:

Function*N*[T1, T2, .., Tn, U]: U {
    def apply(x: T1, y: T2, ..) = {
    }
}

Where

  • N stands for the number of parameters,
  • T1.. Tn are the parameters types
  • and U is the return type

The plusOne method is a Function1 object (because it as only one parameter, an Integer) and a return type of type Int

def plusOne = new Function1[Int, Int] = {

    def apply(x: Int) = x + 1
}

A intToString function, would have a Function1 object type with a String return type:

def intToString = new Function1[Int, String] = {

	def apply(x: Int) = x.toString
}
sum
sumWithoutExplicitReturnType
sumAnonymous
sumObject
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content