COURSE 3 – PROGRAMMING FUNDAMENTALS IN KOTLIN
Week 3: Advanced Classes, Nullability and Collections
Meta Android Developer Professional Certificate
Complete Coursera Answers & Study Guide
Enroll in Coursera Meta Android Developer Professional Certification
TABLE OF CONTENT
- INTRODUCTION
- PRACTICE QUIZ: KNOWLEDGE CHECK: DATA CLASSES
- PRACTICE QUIZ: KNOWLEDGE CHECK: ENUM CLASSES
- PRACTICE QUIZ: KNOWLEDGE CHECK: SPECIAL KINDS OF CLASSES
- PRACTICE QUIZ: SELF-REVIEW: PRACTICE HANDLING NULLABILITY
- PRACTICE QUIZ: KNOWLEDGE CHECK: COLLECTIONS
- PRACTICE QUIZ: SELF REVIEW: PRACTICE USING COLLECTIONS
- QUIZ: MODULE QUIZ: ADVANCED CLASSES AND OBJECTS
- CONCLUSION
Advanced Classes Nullability and Collections INTRODUCTION
In this module, you will learn more about advanced classes and objects in Kotlin. You will learn about List, Set and Map and how these are used while writing code in Kotlin. You will also learn about collections and when to use them.
Learning Objectives
- Demonstrate the handling of nullability
- Describe nullable values
- Describe annotations
- Explore exceptions
- Demonstrate how to iterate over Enum class members
- Describe the Enum class and its uses
- Identify the pair and the triple
- Explain special kinds of classes
- Describe the use of collections in programming
- Identify which collection type to use in any given situation
- Explain the difference between List, Set and Map
PRACTICE QUIZ: KNOWLEDGE CHECK: DATA CLASSES
1. When the following code runs, what will the output be?
class Value(val value: Int)
fun main() {
val value1 = Value(42)
val value2 = Value(42)
println(value1 == value2)
}
- The output will be True
- The output will be False (CORRECT)
Correct! Objects created using a regular class are considered unique, even if they have the same values.
2. When the following code runs, what will the output be?
data class Value(val value: Int)
fun main() {
val value1 = Value(42)
val value2 = Value(42)
println(value1 == value2)
}
- The output will be True (CORRECT)
- The output will be False
Correct! Data class objects are equal to each other when they are of the same class and have the same values in constructor properties.
3. When the following code runs, what will the output be?
class Value(val value: Int)
fun main() {
val value = Value(42)
println(value)
}
- Value@37f8bb67 (CORRECT)
- Value
- 42
- Value@42
Correct! When we print objects created using regular classes, the result will output the class name and the memory address in hexadecimal format.
4. When the following code runs, what will the output be?
data class Value(val value: Int)
fun main() {
val value = Value(42)
println(value)
}
- Value(value=42) (CORRECT)
- 42
- Value
- Value@37f8bb67
Correct! When we print objects created using a data class, the result will output the class name followed by each property name and its corresponding value.
5. When the following code runs, what will the output be?
data class Value(val value: Int)
fun main() {
val (value) = Value(42)
println(value)
}
- Value@{some numbers and letters}
- Value(value=42)
- Value
- 42 (CORRECT)
Correct! Using () brackets, we destructure data class into variables, so variable x is assigned to the value of the first primary constructor property. Therefore, the result is 42.
6. When the following code runs, what will the output be?
data class FullName(
val name: String,
val surname: String
)
fun main() {
val name = FullName("Marie", "Sklodowska")
val newName = name.copy(surname = "Sklodowska-Curie")
println(newName)
}
- FullName(name=Marie, surname=Sklodowska-Curie) (CORRECT)
- FullName(name=Marie, surname=Sklodowska)
- FullName(name=, surname=Sklodowska-Curie)
Correct! The copy method creates a new object with all the values the same as in the original one. If properties are specified, those specific values are changed.
7. What is created when you use the to function between two values?
to "AAA"
- Data class
- Triple (W)
- The second value
- Pair (CORRECT)
- The first value
Correct! The to function will create a Pair.
8. You are programming a coffee machine with a set number of choices and want to specify attributes to each choice. Which one of the following classes will you use?
- Annotation
- Sealed
- Enums (CORRECT)
- Exception
That’s correct! Enums will specify attributes to the set choices you program.
9. You are programming dog names and ages using a data modifier. Which of the following is true about data modifiers? Select all that apply.
- The transformation of the string changes (CORRECT)
- The position of the element is important and it doesn’t matter how variables are named (CORRECT)
- A modified version of the data object can be used (CORRECT)
That’s correct! The properties and values of the dogs are displayed and therefore is a transformation to the string.
That’s correct! Destructuring is based on the position of the elements and it doesn’t matter how variables are named.
That’s correct! The copy function allows for a modified version of the data object to be used.
PRACTICE QUIZ: KNOWLEDGE CHECK: ENUM CLASSES
1. What are the advantages of using enum classes to represent a set of values? Select all that apply.
- When you specify an enum value, you have a suggestion with all the possible values.(CORRECT)
- When a variable is declared as an enum value, only correct enum values can be assigned to it.(CORRECT)
- You can easily enumerate over all enum values. (CORRECT)
- You can easily enumerate over all enum values. enum values are nicely printed.(CORRECT)
Correct! When you specify an enum value, you have a suggestion with all the possible values.
Correct! When an enum variable is declared, only correct enum values can be assigned to it.
Correct! You can easily enumerate over all enum values.
Correct! Enum values are nicely printed.
2.What is the result of the following code?
enum class Letter {
A,
B,
C,
}
fun main() {
println(Letter.C)
}
- C (CORRECT)
- Letter.C
- C@87CEEB
Correct! C is the result of the code.
3. What is the result of the following code?
enum class Letter {
A,
B,
C,
}
fun main() {
println(Letter.B.ordinal)
}
- 1 (CORRECT)
- 3
- 2
- 0
Correct! 1 is the result of the code.
4. What must be added to the following code so that ABC is printed?
enum class Letter {
A,
B,
C,
}
fun main() {
for (l in ______) {
print(l)
}
}
- Letter.values() (CORRECT)
- values()
- letterValues()
- Letter.values
Correct! Letter.values()must be added to the following code so that ABC is printed.
5. What is the result of the following code?
enum class Letter(val smallLetter: Char) {
A('a'),
B('b'),
C('c'),
}
fun main() {
println(Letter.A.smallLetter)
}
- 62
- A
- a (CORRECT)
Correct! The variable smallLetter is set for Letter.A to ‘a’.
6. You are programming three different payment methods for an online shop and use enum classes. Which of the following is a useful feature of enum classes? Select all that apply.
- Enum classes lets you easily iterate over the payment methods (Correct)
- Enum classes still compile code with a typo, but the result will be incorrect
- Enum classes can easily be transformed into a string (Correct)
That’s correct! This is a function that returns an array of payment methods.
That’s correct! An advantage of enum classes is that it can easily be transformed into a string.
PRACTICE QUIZ: KNOWLEDGE CHECK: SPECIAL KINDS OF CLASSES
1. What is the expected result of the following code?
class E: Throwable("E")
fun a() {
print("B")
throw E()
print("C")
}
fun main() {
try {
print("A")
a()
print("D")
} catch (e: E) {
print(e.message)
}
print("F")
}
- ABEF (CORRECT)
- ABCDEF
- ABCEF
Correct! This is the expected result of the code.
2. What is the expected result of the following code?
fun a() {
throw Throwable("Some message")
}
fun main() {
try {
print("A")
a()
} finally {
print("F")
}
}
- A (
- A{exception report}
- AF{exception report} (CORRECT)
- AF
Correct! We haven’t caught an exception, so its report will be printed, but the final block is called anyway.
3. Is the following code going to compile?
enum class PaymentMethod {
CHECK
}
fun makePayment(method: PaymentMethod) {
//...
}
fun main() {
makePayment("CHECK")
}
- No, it will not compile (CORRECT)
- Yes, it will compile.
Correct! String cannot be used where PaymentMethod is expected.
4. What modifier is used to represent restricted hierarchies?
- Private
- abstract
- open
- sealed (CORRECT)
Correct! We used sealed classes (or interfaces) to represent restricted hierarchies.
5. What is a good example of an enum class? Select all that apply.
- Years in general
- Usernames on a social platform
- Months in a year (CORRECT)
- Letters in the alphabet (CORRECT)
Correct! Months in a year are a concrete set of values.
Correct! Letters in the alphabet are a concrete set of values.
6. You have defined an annotation. What happens when you place this annotation in front of a method?
- Annotation code is executed before function call (w)
- Annotation code is executed after function call (w)
- Annotation wraps function body and transforms it
- Nothing (CORRECT)
Correct! Annotation is just a description of our code, and by itself does nothing.
7. Exceptions happen when you try to code and make an illegal operation. To catch the exception you will use ‘try-catch block.’
- Yes (CORRECT)
- No
That’s correct! To catch an exception you will use ‘try-catch block’.
PRACTICE QUIZ: SELF-REVIEW: PRACTICE HANDLING NULLABILITY
1. In step 2 of the exercise, if you pass a null value to getStudentById(130), what will the output of the function be?
- B: Null Pointer Exception (CORRECT)
- Student(fullName=Mark, id=___,grade=120.0)
- Student(fullName=Sara, id=___,grade=130.0)
Correct. The find function will return null, since 130 doesn’t match with any of the stored student IDs.
2. Inside the searchInStudents function, you return a nullable value of Student. If you want to return a non-nullable value, will the following code will achieve that?
fun searchInStudent(name:String):Student{
return stundents.find{it.fullName.lowercase()==name}!!
}
- Yes (CORRECT)
- No
Correct! The assertion operator asserts that a value won’t be null but when the variable value is null, it will throw NPE.
3. Given this piece of code:
val s :String?=null
val l = if (s!=null) s.length else throw NullPointerException()
- val l = s?.length!! (CORRECT)
- val l = if(s!=null) s?.length else -1
- None of the above.
Correct! Using the assertion operatorproduces equivalent code.
4. You have an application and you want users to fill in their names. Which of the following have nullable types? Select all that apply.
- Functions
- Result types (CORRECT)
- Parameters (CORRECT)
That’s correct! Nullable types can be used as result types.
That’s correct! Nullable types can be used as parameters.
5. How can you deal with nulls in Kotlin? Select all that apply.
- Elvis operator (CORRECT)
- Not-null assertion (CORRECT)
- Smart-casting (CORRECT)
- Safe call (CORRECT)
That’s correct! The Elvis operator is used to provide a default value when a value could be null.
That’s correct! The “Not-null assertion” is an unsafe option, as it throws an exception when a value is null.
That’s correct! Smart-casting is used if you add a condition and it allows for treating a variable as not-null after you check that it is not-null.
That’s correct! Safe call means that you call the right side, if the left side is not null.
PRACTICE QUIZ: KNOWLEDGE CHECK: COLLECTIONS
1. Complete the following sentence: “Lists…”. Select all that apply.
- are ordered (CORRECT)
- allow duplicates (CORRECT)
- are collections of elements (CORRECT)
- support getting elements by index (CORRECT)
Correct! All lists are ordered, which means they should respect the initial order of elements.
Correct! Lists allow duplicated elements.
Correct! Lists represent collections of elements, like a list of users on a website or a basket of products.
Correct! You can get an element at a certain index using a box bracket.
2. Complete the following sentence: “Sets…”. Select all that apply.
- do not allow duplicates (CORRECT)
- represent collections of elements (CORRECT)
- can be unordered (CORRECT)
- support getting elements by index
Correct! Sets do not allow duplicates so that their elements are unique.
Correct! Sets represent collections of elements, like a list of products on a website.
Correct! The sets used by default in Kotlin are ordered, but in general, sets might be unordered.
This should not be selected Not quite. Getting elements by index from sets is not supported.
3. Complete the following sentence: “Maps…”. Select all that apply.
- represent collections of elements
- do not allow duplicated keys (CORRECT)
- represent collections of key-value pairs (CORRECT)
- can be unordered (CORRECT)
Correct! Keys in maps must be unique.
Correct! We use maps to represent key-value pairs, and to easily find value for a key.
Correct! Maps used by default in Kotlin are ordered, but in general, maps might be unordered.
4. What is the result of the following code?
fun main() {
val l = listOf("A", "B", "C")
println(l[1])
}
- A
- B (CORRECT)
- C
Correct! B is under the index 1, the index of A is 0.
5. What is the result of the following code?
fun main() {
val l = listOf("A", "B")
val l2 = listOf("D")
print(l + "C" + l2)
print(l)
}
- [A, B, D][A, B]
- [A, B, C, D][A, B] (CORRECT)
- [A, B, C][A, B]
- [A, B, C, D][A, B, C, D]
Correct! This is the correct result for the code.
6. What is the result of the following code?
fun main() {
val s = setOf("A", "B", "A")
print(s)
}
- [A, B] (CORRECT)
- [A, A, B]
- [A, B, A]
Correct! Duplicated A is not allowed.
7. What is the result of the following code?
fun main() {
val m = mapOf('a' to "Alex", 'a' to "Anna")
print(m)
}
- {a=[Alex, Anna]}
- {a=Anna} (CORRECT)
- {a=Alex, a=Anna}
Correct! Maps do not allow duplicated keys.
8. What is the result of the following code?
fun main() {
val m = mapOf('a' to "Alex", 'b' to "Barbara")
print(m['b'])
}
- Barbara (CORRECT)
- 1
- Alex
- null
Correct! By using the box bracket, you get the value from the key, and the value for ‘b’ is “Barbara”.
9. What is the result of the following code?
fun main() {
val m = mapOf('a' to "Alex", 'b' to "Barbara")
print(m['c'])
}
- null (CORRECT)
- Barbara
- Alex
- 1
Correct! When looking for a value for the key that is not present, the result is null.
10. What is the result of the following code?
fun main() {
print(listOf("A", "B", "C").size)
print(setOf(0).size)
print(mapOf('a' to "Alex", 'b' to "Barbara").size)
}
- 212
- 301
- 302
- 312 (CORRECT)
Correct! The size of the list is 3, because it has 3 elements of type String. The size of the set is 1, because it has one element of type Int. The size of the map is 2, because it has 2 key-value associations.
11. You have a list of food choices. What will you use to iterate over the list?
- Size property
- For-loop (CORRECT)
- Plus or minus sign
That’s correct! You will use for-loop to iterate over the list.
12. You want to create an online shop with multiple products and delivery methods. Which one of the following collection types would you use?
- Map
- List (CORRECT)
- Set
That’s correct! You will use lists in this example, because the order of the lists are preserved and will appear in the same order in the payment window.
PRACTICE QUIZ: SELF REVIEW: PRACTICE USING COLLECTIONS
1. You created a Comment class in steps 1 and 2 of the exercise. In these steps, which one of the following Kotlin collections did you use to store the comments of the authors?
- Map
- List (CORRECT)
- Set
That’s correct. You used listOf() to store comments.
2. In step 4, you created the relationship between the user and the author of comments. Which one of the following Kotlin collections did you use to create this relationship?
- List
- Set
- Map (CORRECT)
That’s correct. You used map to create the relationship between the user and the author of comments.
3. In step 5, you filtered and displayed comments. As part of this task, you iterated over the comments list using a for loop.
- True. (CORRECT)
- False.
That’s correct. You started off by iterating over the ‘comments’ list using a ‘for loop.’
Coursera Meta Android Developer Professional Certificate Answers and Study Guide
Liking our content? Then don’t forget to ad us to your bookmarks so you can find us easily!
Weekly Breakdown | Meta Study Guides | Back to Top
QUIZ: MODULE QUIZ: ADVANCED CLASSES AND OBJECTS
1. _________________ is used for classes that are used to represent a bundle of data.
- Data modifier (CORRECT)
- Access modifier
- typeOf
Correct. We use a data modifier for classes that are used to represent a bundle of data.
2. What function of a data class creates a copy of an object
- copyOf
- copy (CORRECT)
- isCopy
Correct. Data classes have `copy` method, that creates a copy of an object.
3. What is the output of the code below?
class Dog(val name: String)
fun main() {
val pluto1 = Dog("Pluto")
val pluto2 = Dog("Pluto")
println(pluto1 == pluto2)
}
- True
- False (CORRECT)
Correct. All objects created with custom classes are considered unique; they are not equal to any other object.
4. What will the output be of the printAddress function in the code below?
class Address(val city: String?, val state: String?) {
}
fun printAddress(address: Address) {
val city: String = address.city ?: "(unknown city)"
val state: String = address.state ?: "(unknown state)"
println("$city $state")
}
fun main() {
printAddress(Address("Lagos", "Lagos"))
}
- Lagos
- Lagos Lagos (CORRECT)
- Lagos (unknown state)
Correct. Since the state is not null, the default name ‘(unknown state)’ will not be used.
5. What is the output of the consumeStr function?
fun consumeStr(str: String?) {
print(str?.length)
print(str?.uppercase())
}
fun main() {
consumeStr("abc")
}
- 3ABC (CORRECT)
- 1AB
- nullnull
Correct. The first print of the consumeStr function displays the length of the string, while the second print displays the uppercase of the string.
6. __________ method is used to check if a set is empty.
- isNull
- isEmpty (CORRECT)
Correct. You can always check the number of elements in a list using size property.
7. What will be the output of the println be?
fun main() {
val list = listOf("A", "B", "C")
println(list[2])
}
- C (CORRECT)
- B
- A
Correct. The position 2 in the list has a value C.
8. What will the output of the println be?
fun main() {
val letters = listOf("A", "B", "C")
println(list.contains("A"))
}
- True (CORRECT)
- False
Correct. The position 0 in the list has a value A.
9. The ____________ class has it constructors protected by default.
- Sealed (CORRECT)
- interface
- abstract
Correct. The sealed classes have a distinct feature, their constructors are protected by default.
10. Enums are defined by using the _____________keyword in front of a class.
- enum (CORRECT)
- typeOf
- data
Correct. Enum classes are used whenever we need to define a specific set of values
11. An instance of enum class can be created using constructors.
- True
- False (CORRECT)
Correct. An instance of enum class cannot be created using constructors?
12. When you run the code below what will the output be of the println statement be?
fun main() {
val (a, b, c) = Triple(2, "x", listOf(null))
println(a)
}
- 2 (CORRECT)
- null
- x
Correct. The println will display 2.
13. Which operator converts a nullable type to its non-nullable form forcibly?
- ==
- ??
- !! (CORRECT)
Correct. Not-null assertion is !! operator, that throws an exception if its left side is null
14. This is an animal interface class; what is missing in the code below?
Animal {
fun bark()
fun run() { // optional body
f}
}
- Sealed Keyword
- Interface keyword (CORRECT)
- Abstract keyword
Correct. An interface keyword must be specified when defining an interface class.
15. A ______________ object does not allow you to directly call any methods or properties on it.
- Nullable (CORRECT)
- Sealed
- Non-Nullable
Correct. When you have a nullable object, you cannot directly call any methods or properties on it.
16. To initialize an immutable list, the _________ function is used.
- listOf (CORRECT)
- list.add()
- mutablelistO
Correct. We create a list using `listOf` function, and then we specify next values using arguments.
17. Interfaces are different from abstract classes as interfaces cannot store state.
- True (CORRECT)
- False
Correct. Interfaces don’t have the capability to store state.
18. __________ is an exception expression, which means it can have a return value.
- finally
- try (CORRECT)
- isNone
Correct. “try” is an expression, which means it can have a return value.
19. You 11 ___________ property.
- Size (CORRECT)
- length
- width
Correct. You can always check the number of elements in a list using `size` property.
20. The code below is a valid implementation of an interface.
interface I {
val a: Int = 123
}
- True
- False (CORRECT)
Correct. You cannot define non-abstract properties in Interfaces.
21. Any class that extends “Throwable” can be used as an exception.
- True (CORRECT)
- False
Correct. Any class that extends “Throwable” can be used as an exception. That means, it can be thrown using “throw” block.
22. The function used to add items to a list is called ____.
- put
- create
- add (CORRECT)
Correct. The easiest way to add elements to lists is using plus sign.
23. True or False: The code snippet below is a valid way of creating an enum in Kotlin.
class Gender{
MALE,
FEMALE
}
- True
- False (CORRECT)
Correct. Enums are defined by using the enum keyword in front of a class
Interactive CSS CONCLUSION
To be written
Subscribe to our site
Get new content delivered directly to your inbox.
Quiztudy Top Courses
Popular in Coursera
- Meta Marketing Analytics Professional Certificate.
- Google Digital Marketing & E-commerce Professional Certificate.
- Google UX Design Professional Certificate.
- Meta Social Media Marketing Professional Certificate
- Google Project Management Professional Certificate
- Meta Front-End Developer Professional Certificate
Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!