Chapter: 18

Functions


Functions


A function is a group of related code that is used to perform a task.

We have seen some functions in action: for example, the println() function is used to output text to the screen:
println("Hello")
KT
The name in front of the parentheses is the function name, and the comma-separated values inside the parentheses are function arguments.
In the example above, println is the function name, "Hello" is the argument.

Functions

How many arguments does the readLine() function in this code have? x = readLine() println(x)

2
none
1

Chapter: 19

Defining Functions


Functions


You can define your own functions and use them in your code.
Functions are defined using the fun keyword, followed by the name of the function:
fun welcome() {
println("Hey there")
}
KT
The code above defines a function named welcome, which has just a single print statement.
The code in the function is called the function's body.

Functions

Fill in the blanks to define a valid function called test:

{

println("42")

}

Functions


After we have defined our function, we can call it in our code:
fun main(args: Array<String>) {
welcome()
}
KT
To call the function, we need to use its name followed by parentheses.
You can call the same function as many times as you need.

Functions

Rearrange the code to call the function "login" in main:

fun main(args: Array<String>)
{
login()
}

Chapter: 20

Function Arguments


Arguments


Arguments provide input to our functions.

For example, let's say we want to pass a name as input to our welcome() function, so that the output included the provided name:
fun welcome(name: String) {
println("Hello, " + name)
}
KT
Our function now takes one argument of type String called name and we can refer to that argument using its name inside the function's body.

When calling this function, you must include an argument within the parentheses:
welcome("James")
welcome("Amy")
KT
Now, the name argument will have the provided value when the function is called.

Arguments

What is the output of this code? fun calc(x:Int) { var y = x*2 println(x+y) } fun main(args: Array<String>) { calc(3) }


Arguments


We can provide multiple arguments to our function, separating them with commas.
For example, let's define a function that outputs the sum of its two arguments:
fun sum(x: Int, y: Int) {
println(x+y)
}
fun main(args: Array<String>) {
sum(8, 5)
}
KT
The arguments are passed to the function in the same order as they are declared.

Arguments

Fill in the blanks to define a function that takes two Int arguments and outputs the larger one.

fun

max(a:Int, b:

Int

) {


if(a>=b) {


println(

a

)


}


else

{


println(b)


}


}


Chapter: 21

Returning from Functions


Returning from Functions


So far we have seen functions that output a value.

In some cases there is a need for a function to return a value, so that it can be assigned to a variable.

For example:
var result = sum(8, 42)
KT
For this, we need to define the return type for our sum function, and use the return keyword to return the result:
fun sum(x: Int, y: Int): Int {
return (x+y)
}
KT
Our sum function now takes two Integer arguments and returns an Integer as the result.
Note, that the return type is provided after the parentheses, but before the body of the function.

Returning from Functions

Fill in the blanks to define a function which returns true, if its Integer argument is larger than 18, and false, if not.

fun allowed(age:

Int

):

Boolean

{


if

(age > 18) {


return

true


}


else {


return

false


}


}


Chapter: 22

Anonymous Functions


Anonymous Functions


Not all functions need a name. In some cases the function does a very simple task with it's input.
In these cases its simpler to define an anonymous function.

Let's define our sum() function from the previous lessons as an anonymous function:
val f: (Int, Int) -> Int = { a, b -> a+b }
KT
Our function needs to take two Integer inputs and return their sum. That is why the type of the function is (Int, Int) -> Int. The parentheses define the input type, while the arrow defines the return type.
Inside the body of the function we have named our input arguments a and b, and used the arrow to return their sum.

Anonymous Functions

How many arguments does a function with the type (String)->Int take?

none
1
2

Anonymous Functions


Now, when we have our anonymous function defines, we can assign it a variable and use it in our code, just like a normal named function:
val f: (Int, Int) -> Int = { a, b -> a+b }
var result = f(8, 42)
println(result)
KT
In the code above, we assigned the anonymous function to the variable f and used f to call it.
The anonymous function can be shortened as: val f = { a:Int, b:Int -> a+b } because Kotlin automatically understands the return type from the arguments.



forEach Loop


Oftentimes there is a need to perform an action with all items of an array.
Kotlin provides a forEach loop, which takes a function, defining the action to perform with each of the array elements.

For example:
fun main(args: Array<String>) {
var arr = arrayOf(1, 3, 5)
arr.forEach {
item -> println(item * 4)
}
}
KT
The forEach loop is called using the name of the array and a dot, which should be followed by a function.
In the code above, we name each element of the array item and output the value of item times 4.
Kotlin provides an it keyword for the name of the elements in forEach. This allows you to shorten the code to the following:
arr.forEach {
println(it * 4)
}

Chapter: 23

Higher-order Functions


Higher-order Functions


A function can take another function as an argument. These functions are called higher-order functions.
This is useful when we want to change the behavior of a function.
For example:
fun apply(x:Int, action: (Int) -> Int): Int {
return action(x)
}
KT
apply is a higher-order function which takes an integer and a function named action as its arguments.
Then it calls the action function on its integer argument and returns the result.

Now we can call our apply function and pass it different anonymous functions as the action argument:
println(apply(4, {x -> x*2}))
println(apply(4, {x -> x/2}))
KT
As you can see, our anonymous functions don't need to define the type of its argument, because Kotlin automatically guesses it.

Higher-order Functions

Which function in this code is a higher-order function? fun square(a: Int): Int { return a*a } fun doStuff(x:Int, func: (Int) -> Int): Int { return func(x) }

square
doStuff

Higher-order Functions


Kotlin has many higher-order functions.
For example, the filter() function of an array takes a Boolean function and returns the elements that match the given condition.

For example, let's filter only the elements that are greater than 5:
val arr = arrayOf(42, 3, 10, 4, 6, 1)
val res = arr.filter({ it > 5 })
println(res)
KT
This will result in only the elements that are greater than 5.

Practice:

Filtering Names


You are given an array of names and need to output only the names that start with the given letter.
The letter should be taken from user input.
Each of the resulting names should be output on a separate line.
The given code takes the letter as input.

Chapter: 24

Module 3 Quiz




What is the output of this code? fun f(x: String): Int { var z = 0 for(a in x) { z++ } return z } fun main(args: Array<String>) { println(f("hello")) }





Code Project:

Shipping Calculator


Shipping Calculator


You are working on a eCommerce website and need to make a shipping cost calculator based on the order amount.
The store uses the following cost structure:
For orders in the US:
- $75+ orders have free shipping
- orders less than $75 have a shipping fee of 10% of the total order amount.

For international orders, there is a 15% shipping fee, with a maximum of $50. This means that the maximum shipping fee for an international order is $50.

You need to complete the given shippingCost() function, which takes the order amount and a Boolean indicating whether the order is international or not, and returns the shipping cost for that order.
The return amount should be a Double.

Sample Input:
140.0
true

Sample Output:
21.0

Note: comment down your answer.
The order is for $140 and is international. So, the shipping cost would be 15%, which is $21.