COURSE 6: ADVANCED PROGRAMMING IN KOTLIN QUIZ ANSWERS

Week 3: Functional Programming

Meta Android Developer Professional Certificate

Complete Coursera Answers & Study Guide

Enroll in Coursera Meta Android Developer Professional Certification

INTRODUCTION

Learn about Lambda expressions, Function types, Higher-order functions and collections processing. Explore how functions can be used as objects, how to use lambda expressions to define functions as objects and how to define and use higher-order and repeat functions. Finally, exploited using collection processing methods with multistep collection processing.

Learning Objectives

  • Explain what functional programming is and why it is useful.
  • Read and define a function type.
  • Use a lambda expression to define a function as an object.
  • Define a function that takes a function as an argument.
  • Use collection processing functions to process collections in different ways.
  • Use collection processing methods for multistep collection processing.

SELF REVIEW: PRACTICE DEFINING LISTENERS IN ANDROID

1. In the Practice defining listeners in Android exercise, when you ran the code, what did the app show on its screen?

  • A button with text Save Data written on it. (CORRECT)
  • Empty screen
  • Toast message with text – Data saved

Correct! You implemented the button code correctly in the layout file. 

2. What was the result of clicking the button with text Save Data?

  • A toast message with text – Data saved appears on the screen. (CORRECT)
  • Nothing happens
  • Button disappears

Correct! You implemented the click listener using a lambda expression correctly. 

3. Choose the options with the correct lambda expression syntax implementation.

  • button.setOnClickListener { view ->  println(view.id) } (CORRECT)
  • button.setOnClickListener { println(it.id) } (CORRECT)
  • button.setOnClickListener( println(it.id) )

Correct! You can define a lambda expression without the parenthesis if the only parameter is the lambda itself and then can define an arbitrary name to the lambda parameter. 

Correct! You can define a lambda expression without the parenthesis if the only parameter is the lambda itself and then can if no arbitrary name is assigned to the lambda parameter, access it using it keyword.

5. What are the benefits of using a function as an object? Check all that apply.

  • You don’t need to use any variables
  • You can pass functions to other functions (CORRECT)
  • The relationship between classes is loosened (CORRECT)

That’s right! You can pass a function as a parameter to another function.

Correct! You can execute a function object directly, instead of accessing it through its parent class.

6. Which of these represents a syntactically valid function type?

  • nt, Int -> (String)
  • (Int, Int) -> String (CORRECT)
  • (Int) -> Int, String

Correct! You define the list of parameters enclosed in a parenthesis, followed by arrow notation and the return type.

7. A lambda expression is a simple way to define a function as what? 

  • a constant
  • a parameter
  • an object (CORRECT)
  • a variable

That’s correct. Lambda allows you to define a function as an object and you can then call it just as you call regular functions.

8. You have a button variable referencing a button component. How do you listen to click events on that button?

  • button.performClick()
    button.setOnClickListener(object : OnClickListener {
        override fun onClick(v: View?) { /* Do something */ }
    }) (CORRECT)
  • button.setOnClickListener { /* Do something */ } (CORRECT)
  • button.callOnClick()

That’s right! Passing in an anonymous OnClickListener will listen to click events. Android Studio will recommend replacing this with a lambda.

That’s right! Passing a lambda to the setOnClickListener function will listen to click events.

KNOWLEDGE CHECK: LAMBDA EXPRESSIONS

1. Which of these are correct ways to instantiate a function type. Select all that apply.

  • Using a lambda expression. (CORRECT)
  • Using a callable reference to existing declaration using the ‘::’ operator  (CORRECT)
  • Using instance of a user defined class that implements a function type as an interface. (CORRECT)
  • Using the function name.

Correct! You can use a lambda expression to instantiate a function type.

Correct! You can use a callable reference such as ‘::functionName’.

Correct! You can instantiate a function using a defined class that implements a function type as an interface.

2. Which of these is a syntactically valid function type?

  • Int, Int -> (String)
  • (Int) -> Int, String
  • (Int, Int) -> String (CORRECT)

Correct! You define the list of parameters enclosed in a parenthesis, followed by arrow notation and the return type.

3. Which of these is a correct lambda expression syntax?

  • { x: Int, y: Int -> x * y } (CORRECT)
  • x: Int, y: Int -> { x * y }
  • x: Int, y: Int -> x * y

Correct! This is the correct syntax.

4. Which of these would output ‘hello world’ when the function defined below is called?

fun execute(string: String, function: (String) -> String) { 
println(function(string))
}
  • execute { “hello world” }
  • execute(“hello”) { “world” }
  • execute(“hello”) { “$it world” }  (CORRECT)

Correct! The implicit argument ‘it’ will contain the value ‘hello’ and hence concatenated string, ‘hello world’ will be printed.

5. Which listener interface provided by the Android framework is used to listen for button press events?

  • View.OnTapListener
  • View.OnPressListener
  • View.OnClickListener (CORRECT)

Correct! The ‘View’ class contains an interface ‘OnClickListener’ that has a method ‘onClick’ which gets called on events such as a button press.

SELF REVIEW: THE REPEAT FUNCTION

1. While the code in The repeat function exercise uses a function to generate random numbers, which of the following is a valid output for the wheel spin attempts?

  • Attempt 1: 4 
    Attempt 2: 8
    Attempt 3: 5 (CORRECT)
  • Attempt 1: 3.25
    Attempt 2: 6.5
    Attempt 3: 8
  • Attempt 1: 3 
    Attempt 2: 10
    Attempt 3: 8

Correct! Random.nextInt(10) can return integer values from 0 to 9.

2. Which of the following is the correct function definition for the repeat function?

  • fun repeat(action: (Int) -> Unit)
  • fun repeat(times: Int, action: () -> Unit)
  • fun repeat(times: Int, action: (Int) -> Unit) (CORRECT)

Correct! The first parameter represents the number of iterations and the second parameter represents a function type which takes in an integer parameter with its value as the index position in the iteration.

3. Which of the following constructs is the repeat function similar to? 

  • While loop
  • If statement
  • For loop (CORRECT)

Correct! The repeat function is similar to a for loop where you define the number of iterations beforehand. 

4. Which of these correctly describes a higher order function?

  • A function that receives a function as an argument and returns an integer (CORRECT)
  • A function that receives as string and returns a function as a return value (CORRECT)
  • A function that always returns an integer. 
  • A function that has an argument of type String.

Correct! This is one of the qualities of higher order functions.

That’s right! This is one of the qualities of higher order functions.

5. A function that lets you define a function as a parameter to be executed inside the function is a higher-order function.

  • True (CORRECT)
  • False

That’s correct. A higher-order function lets you define a function as a parameter to be executed inside a function.

KNOWLEDGE CHECK: HIGHER ORDER FUNCTIONS

1. What is a higher-order function?

  • A function that takes functions as parameters, or returns a function. (CORRECT)
  • A higher-order function is a function that does not return any value.
  • A function that depends on another function for its output.

Correct! A higher-order function is a functional programming concept that allows function to be passed just as objects of other data types.

2. Which of these is a correct way to call the function greet:

fun greet(name: String, function: (name: String) -> Unit) {
  function(name)
}
fun print(name: String) {
  println("Hello $name")
}
  • greet { print(it) } (“Joe”)
  • greet(“Joe”) { println(“Hi $it”) } (CORRECT)
  • greet(“Joe”, print)
  • greet(“Joe”, ::print) (CORRECT)

Correct! You can pass a function as a lambda expression to a higher-order function.

Correct! You can use the :: operator to obtain the reference of a function.

3. Which of the following constructs is the repeat function similar to? 

  • for loop (CORRECT)
  • while loop 
  • If statement 

Correct! The repeat function is similar to a for loop where you define the number of iterations beforehand.

4.  What is the output of the following code?

val number = 2
var output = 1
repeat(3) { index ->
 output += (index * number)
}
println(output)
  • SELF REVIEW: PROCESS COLLECTIONS7 (CORRECT)
  • 6
  • 13

Correct, this is the right result.

SELF REVIEW: PROCESS COLLECTIONS

1. What was the sales tax amount output (up to 2 decimal places) when you ran your exercise’s code?

  • 9.59 (CORRECT)
  • 8.98
  • 7.71

Correct! You correctly implemented the exercise instructions.

2. What would be the sales tax output (up to 2 decimal places) if you change the month to August and the sales tax percentage to 7.5%?

  • 5.02 (CORRECT)
  • 4.95
  • 6.38

Correct! You correctly implemented the exercise instructions.

3. Which of the following functions does not return a List when called on an instance of List?

  • filter
  • fold (CORRECT)
  • map

Correct! The fold function would return an accumulated value starting from an initial value and applying an operation to an accumulated value and each element. 

4. Which of the following are the steps involved in collection processing? 

  • Select all that apply.      
  • Defining and applying the operation on the element.   (CORRECT) 
  • The value held in an optional cannot be directly accessed.  (CORRECT)    
  • Defining and applying the elements of an optional operation.      
  • Accessing elements of a collection on which the operation is to be applied.  (CORRECT)

That’s correct!  This is the second step in collection processing.      

That’s correct! This is the final step in collection processing.     

That’s correct!  This is the first step in collection processing. 

5. forEach is an excellent example of an extension function and of a higher-order function.       

  • True (CORRECT)
  • False

That’s correct. forEach is an excellent example of an extension function and of a higher-order function.

6. After map takes a transformation lambda as an input, what occurs next?    

  • It applies this function to every element and returns a list of the transformed outputs. (CORRECT)      
  • It applies this function to specified elements and returns a list of the transformed outputs.      
  • It applies this function to every element and returns the original element.   

That’s correct. Map applies this function to every element and returns a list of the transformed outputs.     

7. You would use filter when you are only interested in some elements of your collection.   

  • True (CORRECT)
  • False

That’s correct. You use filter when you are only interested in some elements of your collection.      

8. If you are only interested in some elements in your collection, which function would you use?      

  • Filter (CORRECT)
  • map
  • fold
  • forEach

That’s correct. filter() is used to return a subset of the original collection based on a predicate.    

9. If you want to process a Kotlin collection and return a modified collection, you could use Kotlin’s collection processing functions.       

  • True (CORRECT)
  • False

That’s correct. Kotlin’s collection processing functions operate on a target collection and return the result collection.       

KNOWLEDGE CHECK: COLLECTIONS PROCESSING

1. What is the output of the following code?

var sum = 0
val numberList = listOf(2, 8, 3, 11) 
numberList.forEach { number ->
 sum += number
}
println(sum)
  • 2
  • 24 (CORRECT)
  • 11

Correct! The code would iterate over each element and then add each element’s value to a variable named sum.

2. What is the output of this code:

data class Car(
val color: String,
val amount: Int
)
val list = listOf(
 Car("Black", 43000),
 Car("Red", 30000),
 Car("White", 36000)
)
val output = list.map { 
 it.color
}
println(output)
  • [Black, Red, White] (CORRECT)
  • [Car(color=Black, amount=43000), Car(color=Red, amount=30000), Car(color=White, amount=36000)]
  • [43000, 30000, 36000]

Correct! The code transforms the initial list into a new list that contains values of color.

3. What do you expect to get as the output of this code?

val list = listOf(1, 3, 4, 7)
val output = list.fold(3) { x, y ->
 x + y
}
println(output)
  • 18 (CORRECT)
  • 12
  • 3

Correct! The fold function accumulates a value starting from the initial value of 3 and then applies the operation to each element in the list.

4. What output would you expect for this code?

val numberMap = mapOf(
 5 to 6,
 3 to 2,
 8 to 7,
 4 to 1
)
val output = numberMap.map { entry ->
 entry.value
}.filter { 
 it > 3
}.fold(0) { x, y ->
 x + y
}
println(output)
  • 3
  • 13 (CORRECT)
  • 17

Correct! You correctly computed the outputs of the map, filter and fold functions in the code.

5. What is the output of the code below:

data class Car( 
val color: String, 
val amount: Int 
) 
val list = listOf( 
  Car("Black", 43000), 
  Car("Red", 30000), 
  Car("White", 36000) 
)  
val output = list.filter { car -> 
  car.amount > 35000 
} 
println(output)
  • [Car(color=Black, amount=43000), Car(color=Red, amount=30000), Car(color=White, amount=36000)]
  • [Car(color=Red, amount=30000)]
  • [Car(color=Black, amount=43000), Car(color=White, amount=36000)] (CORRECT)

Correct! This code above filters the ‘car’ elements that have ‘amount’ > 35000, and returns a new list with only those elements that comply with the condition.

MODULE QUIZ: FUNCTIONAL PROGRAMMING

1. Which of these are correct ways to instantiate a function type. Select all that apply.

  • Using a callable reference to existing declaration using the ‘::’ operator  (CORRECT)
  • Using instance of a user defined class that implements a function type as an interface.  (CORRECT)
  • Using a lambda expression.  (CORRECT)
  • Using the function name.

Correct! You can use a callable reference such as ‘::functionName’.

Correct! You can instantiate a function using a defined class that implements a function type as an interface.

Correct! You can use a lambda expression to instantiate a function type.

2. Which of these is a correct usage of lambda expression for the given function definition?

fun execute(number: Int, function: (Int) -> String) {
 println(function(number))
}
  • execute(“Score”) { “$it 100” }
  • execute(100) ( “Score $it” )
  • execute(100) { “Score $it” } (CORRECT)

Correct! The above function takes in an ‘Int’ argument and then prints a string by concatenating it with the ‘Score’.

3. Which of the these is a correct lambda expression syntax?

  • val difference: (Int, Int) -> Int = x: Int, y: Int -> x – y
  • val difference: (Int, Int) -> Int = { x: Int, y: Int -> x – y } (CORRECT)
  • val difference: (Int, Int) -> Int = x: Int, y: Int -> { x – y }

Correct! This is the correct syntax

4. Which listener interface provided by the Android framework is used to listen for a button press event?

  • View.OnTapListener
  • View.OnClickListener (CORRECT)
  • View.OnPressListener

Correct! The ‘View’ class contains an interface ‘OnClickListener’ that has a method ‘onClick’ which gets called on events such as a button press.

5. Which of these are higher-order functions? Select all that apply.

  • fun display(x: (Int) -> Unit)  (CORRECT)
  • fun display(x: Int) : Unit
  • fun display(x: (Int)) -> Unit
  • fun display(): (Int) -> Unit  (CORRECT)

Correct! This is a higher-order function as it takes another function as a parameter.

Correct! This is a higher-order function as it returns a function.

6. What is the output of this code?

val number = 3
var output = 2
repeat(5) { index ->
 output += (index * number)
}
println(output)
  • 30
  • 32 (CORRECT)
  • 47

Correct! You correctly calculated the output of the given code.

7. What is the output of the following code?

var sum = 0
val numberList = listOf(1, 4, 6, 7, 9) 
numberList.forEach { number ->
 sum += number
}
println(sum)
  • 9
  • 27 (CORRECT)
  • 1

Correct! The above code would iterate over each element and then add each element’s value to variable named ‘sum’.

8. What is the output of this code:

data class Chocolate( 
 val flavor: String, 
 val price: Int 
) 
val list = listOf( 
 Chocolate("Dark", 7), 
 Chocolate("Milk", 4), 
 Chocolate("Coffee", 2) 
)
val output = list.map { 
 it.flavor 
} 
println(output)
  • [7, 4, 2]
  • [Chocolate(flavor=Dark, price=7), Chocolate(flavor=Milk, price=4), Chocolate(flavor=Coffee, price=2)]
  • [Dark, Milk, Coffee] (CORRECT)

Correct! The above code would iterate over each element and then add each element’s value to variable named ‘sum’.

9. What is the output of this code:

data class Chocolate( 
 val flavor: String, 
 val price: Int 
) 
val list = listOf( 
 Chocolate("Dark", 7), 
 Chocolate("Milk", 4), 
 Chocolate("Coffee", 2) 
)
val output = list.filter { 
 it.price > 3
} 
println(output)
  • [Chocolate(flavor=Dark, price=7), Chocolate(flavor=Milk, price=4)] (CORRECT)
  • [Chocolate(flavor=Dark, price=7), Chocolate(flavor=Milk, price=4), Chocolate(flavor=Coffee, price=2)]
  • [Chocolate(flavor=Coffee, price=2)]

Correct! The code above filters the ‘chocolate’ elements that have ‘price’ > 3, and returns a new list with only those elements that comply to the condition.

10. What is the output of this code:

val list = listOf(9, 3, 1, 6) 
val output = list.fold(1) { x, y -> 
 x + y 
} 	
println(output)
  • 1
  • 20 (CORRECT)
  • 18

Correct! The fold function accumulates a value starting from the initial value of ‘1’ and then applies the operation to each element in the list.

CONCLUSION

tbw

Subscribe to our site

Get new content delivered directly to your inbox.

Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!