COURSE 6: ADVANCED PROGRAMMING IN KOTLIN QUIZ ANSWERS

Week 2: Advanced Object-Oriented Features

Meta Android Developer Professional Certificate

Complete Coursera Answers & Study Guide

Enroll in Coursera Meta Android Developer Professional Certification

Advanced Object-Oriented Features INTRODUCTION

Learn how to add methods to classes using extension functions while defining and using extension functions in Android. Then explore functions for different kinds of collection processing using map, filter, and fold.

Learning Objectives

  • Use an extension function to add a method to a class when appropriate.
  • Explain a testing methodology called Test-Driven Development
  • Explain the features of Test-Driven Development (TDD)
  • Explain the purpose and types of testing.
  • Use mocks and fakes for unit testing in Android
  • Define and use a generic class to solve a problem

SELF REVIEW: EXTENSIONS

1. What was the output when you ran your solution?

  • Onion,
  • Cheese,
  •  Water
  • [Onion, Cheese, Water, Salt] 
  • [Onion, Cheese, Water] (CORRECT)

Correct! This is how Kotlin’s println outputs a list of strings and these are the ingredients that remain in the onion soup dish after removing salt. 

2. Replace the Salt string in the removeSalt extension function with Cheese. Run the code. What is the output?

  • [Onion, Water]
  • [Onion, Cheese, Water]
  • [Onion, Water, Salt] (CORRECT)

Correct! Salt is no longer removed from the list. Instead, cheese is removed. 

3. Little Lemon asks you to write a new extension function to remove an ingredient (provided as a string) from a dish. Which of these extension functions will perform the requested task?

  • fun String.removeIngredient(dish: Dish) { dish.ingredients.remove(this) } (CORRECT)
  • fun Dish.removeIngredient(ingredient: String) { ingredients.remove(ingredient) }  (CORRECT)
  • fun String.removeIngredient(ingredient: String) { remove(ingredient) } 

Correct! This function will extend the String class with the capability of removing ingredients from a provided dish. 

Correct! This function will extend Dish with the capability of removing ingredients by name. 

4. In Kotlin an extension function allows programmers to add functionality by inheriting from existing classes.

  • True
  • False (CORRECT)

That’s correct. An extension function allows programmers to add functionality without inheriting from existing classes.

5. To add an extension function to a class, you

  • Define a new function appended to the method name
  • Define a new function using the Extension keyword
  • Define a new function appended to the class name (CORRECT)
  • You cannot add an extension function to a class

That’s correct. Defining an extension function is the same as a regular function with a class name prefix.

KNOWLEDGE CHECK: EXTENSIONS

1. Which of the below can be inherited? Select all that apply.

  • An interface (CORRECT)
  • An open class (CORRECT)
  • A final class
  • An object

Correct! Interfaces are designed to be inherited.

Correct! Open classes are open for extension and can be inherited.

2. Extension functions can be quite useful. Which of these are benefits of extension functions? Select all that apply.

  • They allow extending final and 3rd party classes. (CORRECT)
  • They can be called just like normal functions of the extended class. (CORRECT)
  • They can override existing functions of a class.
  • They can access private properties and functions of the extended class.

Correct! Extension functions let you extend behavior of classes that cannot or should not otherwise be modified.

Correct! Extension functions are called using the same syntax as normal functions.

3. You are asked to implement an extension function for the final Dish class that would print out its ingredients field. How would the extension function look?

  • fun List<Ingredient>.printIngredients(dish: Dish) { println(this) }
  • fun Dish.printIngredients(ingredients: List<Ingredient>) { println(ingredients) }
  • fun Dish.printIngredients() { println(ingredients) } (CORRECT)
  • fun printIngredients(dish: Dish) { println(dish.ingredients) }

Correct! This is the right syntax for the requested extension function.

SELF REVIEW: WRITE A UNIT TEST

1. How do you convert the regular function into the test function?

  • Append test_ prefix to the function name.    
  • Mark the class where it is located with Test annotation.
  • Mark the function with Test annotation. (CORRECT)

Correct! Test annotation enables the function be to run as test.

2. What is the correct order of AAA pattern?

  • Act – Arrange – Assert
  • Arrange – Act – Assert (CORRECT)
  • Assert – Act – Arrange

Correct! First, you set up the test environment. Next, execute the operation under test and then, examine the outcome.    

3. Which of three tests for Product class will fail, if you change the minimum amount for discount from 5 to 10? (Hint: update the applyDiscount function and see)  

  • Only the second test will fail. (CORRECT)
  • All tests will fail.
  • The first and the second tests will fail.

Correct! The first test case still passes, as given amount for spaghetti, 3, is still less than minimum amount and it is eligible for discount, while the last test case (out of stock), is not affected by changes.   

4. What types of test is used to validate whether a software application meets its specified requirements? Select all that apply. 

  • Check the reliability and scalability of software application 
  • Check correctness and completeness 
  • Discover performance and security issues 
  • All of the above (CORRECT)

Correct! These are some of the reasons to test software

5. What types of test is used to validate whether a software application meets its specified requirements?

  • Non-functional testing
  • Functional testing (CORRECT)
  • Both functional and non-functional testing

That’s correct. Functional testing techniques such as unit, integration and end-to-end testing are used to verify whether a software application meets itsspecified requirements.

6. You have an instance of a class named classUnderTest. It has a function called isActive that should return true. How would you verify it works as expected?

  • assertEquals(true, classUnderTest.isActive() (CORRECT)
  • assertEquals(classUnderTest.isActive, true)
  • valresult =classUnderTest.isActive()
  • assertEquals(true, classUnderTest)

That’sright! If isActive() returns true, the test will pass. If isActive() returns false, assertEquals will throw an exception and the test will fail.

SELF REVIEW: DEFINING GENERIC CLASSES AND FUNCTIONS

1. When you run your solution for the exercise Defining generic classes and functions, what is the output?

  • 1
  • 2 (CORRECT)
  • [Cheese, Cheese]

Correct! Since addIngredient was called twice, contents holds two elements.

2. If you replaced the type passed to newInventory from Cheese to Onion, when you run your solution, which of the following would be a valid statement?

  • cheeseInventory.addIngredient(Cheese)
  • cheeseInventory.addIngredient(“Onion”)
  • cheeseInventory.addIngredient(Onion)

Correct! After your change, the addIngredient function of cheeseInventory only accepts arguments of type Onion.

3. For the code implemented in Step 2 of the exercise, which of the below statements are valid? 

  • Inventory<Egg>() (CORRECT)
  • Inventory<Flour>() (CORRECT)
  • Inventory<“Milk”>()

Correct! Egg inherits from Ingredient and is therefore a valid generic type for Inventory.

Correct! Flour implements Ingredient and is a valid generic type for Inventory. 

4. Once features and software requirements are planned, what is the next step in a test-driven development approach?

  • Writing tests (CORRECT)
  • Writing code to implement requirements
  • Refactoring code to fix errors
  • Executing tests

Correct. The tests are written first such that they cover the scenarios of software application requirements. Later, code is written with the intent of passing the tests.

5. Which of the following problems could be solved using collections and collection functions?

  • Given a list of restaurant orders, you want to print them out in an ascending date order.  (CORRECT)
  • Given a string containing a first and last name, you want to return a string containing the values in reverse order.
  • Given a list of students, you want to extract a list of Grade A students. (CORRECT)
  • You want to implement a function that multiplies an integer by 2.

That’s right. Having a list of orders, sorting them, and printing them out are good examples of using collections and collection functions.

That’s right. Extracting a list from another list based on certain criteria is a good example of using collections and collection functions.

6. Given a generic class defined as:

class Item<T>(t: T) {
    val value = t
}

What will the type of T be for a variable which is initialized as Item(2.0f)?

  • Float (CORRECT)
  • Int
  • String

That’s correct! 2.0f is a value of type Float, and hence the parameterized type T would be Float.

7. Let’s say you wish to write a function that prepares a dessert. Which of these is the correct syntax for such a function?

  • fun T prepareDessert (item: <T : Dessert>)
  • fun <T : Dessert> prepareDessert(item: <T : Dessert>)
  • fun <T : Dessert> prepareDessert (item: T) (CORRECT)

Correct! You define the upper bound constraint for the generic type beforethe name of the function.

KNOWLEDGE CHECK: COLLECTIONS AND GENERICS

1. What operations can you perform on a MutableCollection but not on a Collection? 

  • Get a count of the elements in the collection.
  • Read an element.
  • Remove an element. (CORRECT)
  • Add an element. (CORRECT)

Correct! You can only remove an element from a MutableCollection.

Correct! You can only add an element to a MutableCollection.

2. Which of the following statements declares a generic class in Kotlin?

  • class GenericClass<TYPE> (CORRECT)
  • class GenericClass
  • generic class GenericClass
  • abstract class GenericClass

Correct! This is the right syntax for declaring a generic class.

3. You need to instantiate a field named employeeNames of type List<String>. Which of the following statements is valid in Kotlin?

  • val employeeNames: List<String> = listOf(“James”, “Ella”) (CORRECT)
  • val employeeNames: List<String> = [“James”, “Ella”]
  • val employeeNames: List<String> = “James, Ella”
  • val employeeNames: List<String> = (“James”, “Ella”)

Correct! This is the correct syntax for instantiating a list of strings.

MODULE QUIZ: ADVANCED OBJECT-ORIENTED FEATURES

1. For a class Rectangle, which of these represents the correct syntax for defining an extension function getWidth?

  • fun Rectangle getWidth(): Int
  • fun Rectangle.getWidth(): Int (CORRECT)
  • fun getWidth<Rectangle>(): Int

Correct. You use the dot operator after the class name and before the function name to define an extension function.

2. For the extension function fun Rectangle.getWidth(): Int, what is the correct way to call the function in the code?

  • Rectangle.getWidth()
  • Rectangle().getWidth()
  • getWidth(Rectangle())

Correct!

3. Which type of testing is performed to test individual components of an application’s code logic?

  • Integration testing
  • Unit testing (CORRECT)
  • End-to-end testing

Correct. Unit testing is performed to test individual components, also known as the unit under test.

4. While using JUnit, which annotation is used to mark a function as a unit test?

  • @UnitTest
  • @Test (CORRECT)
  • @JUnitTest

Correct. You use @Test annotation to mark a function as a test.

5. When should you use mocks in your tests?

  • When you need to define a complete alternate definition of an object to be used for testing.
  • When there are objects that are not to be tested but are needed because the code under test depends on them. (CORRECT)
  • When you need to test only some specific behavior of an object

Correct. You use mocks to simulate the behavior of objects that the test code depends on.

6. Which of these is a definition of the List collection type?

  • An unordered group of elements that cannot contain duplicate elements.
  • An ordered group of elements that can contain duplicate elements. (CORRECT)
  • An unordered group of elements that can contain duplicate elements.

Correct. A List is an ordered group of elements that can contain duplicate elements.

7. What is the output of the code below:

  1. val numberSet = setOf(185752)println(numberSet)

  • [1, 8, 5, 7, 5, 2]
  • [1, 8, 5, 7, 2] (CORRECT)
  • [1, 8, 7, 2]

Correct. A set cannot contain duplicate elements.

8. What is the output of the following code:

val map = mapOf(
 1 to 90, 
 2 to 93,
 3 to 91,
 4 to 93,
 2 to 95,
 5 to 93
)
println(map)
  • {1=90, 2=93, 3=91, 4=93, 5=93}
  • {1=90, 2=95, 3=91, 4=93, 5=93} (CORRECT)
  • {1=90, 2=93, 3=91, 4=93, 2=95, 5=93}

Correct. A map stores unique keys, but the values do not have to be unique.

9. Which of these represents the correct syntax for defining a generic class?

  • class <T> Item(t: T) { }
  • class Item<T>(t: T) { } (CORRECT)
  • class <T>.Item(t: T) { }

Correct. The generic parameter enclosed in the angle brackets is written after the class name.

10. Which of these represents the correct syntax for defining a generic function?

  • fun sampleFunction<T> (item: T) { }
  • fun <T> sampleFunction(item: T) { } (CORRECT)
  • fun <T>.sampleFunction(item: T) { }

Correct. Generic type parameters are placed before the name of the function.

Interactive CSS 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!