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
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)
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")
}
println("Hey there")
}
KT
The code in the function is called the function's body.
Functions
Fill in the blanks to define a valid function called test:
Functions
After we have defined our function, we can call it in our code:
fun main(args: Array<String>) {
welcome()
}
welcome()
}
KT
You can call the same function as many times as you need.
Functions
Rearrange the code to call the function "login" in main:
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)
}
println("Hello, " + name)
}
KT
When calling this function, you must include an argument within the parentheses:
welcome("James")
welcome("Amy")
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)
}
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.
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
fun sum(x: Int, y: Int): Int {
return (x+y)
}
return (x+y)
}
KT
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.
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
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?
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)
var result = f(8, 42)
println(result)
KT
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)
}
}
var arr = arrayOf(1, 3, 5)
arr.forEach {
item -> println(item * 4)
}
}
KT
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)
}
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)
}
return action(x)
}
KT
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}))
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) }
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)
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.









0 Comments