FP Module 2 - 101 Scala
Bubu
7,372 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Function (basics)
Function declaration
A Scala function declaration looks like :
def functionName ([list of parameters]) : [return type]
This function is an abstract function (because there is no definition (~body) associated with the declaration).
Function definition
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 (make an automatic deduction of 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).
Define the double function
Define the plusOneThenDouble function
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package fp101.tp01.functions
object ExerciceFunctionsBasics {
/**
*
* Define the double function that takes an Integer x as parameter
* and return the double of x
*
* For instance, double(4) gives 8
*/
def double(x: Int): Int = ???
/**
* Define the function plusOneDouble that take an Integer x as parameter, add one to x
* and then return the double of the updated value
*
* For instance, plusOneDouble(4) gives 10
*
* hint: Use the double function inside your plusOneDouble function
*/
def plusOneThenDouble(x: Int): Int = ???
}
Enter to Rename, Shift+Enter to Preview