Recall & Review
beginner
What is an extension function in Kotlin?
An extension function lets you add new functions to existing classes without changing their source code. It looks like a normal function but is called as if it belongs to the class.
Click to reveal answer
beginner
How do you declare an extension function for the String class that returns the first character?You write:
fun String.firstChar(): Char = this[0]This adds a function called firstChar() to all String objects.
Click to reveal answer
intermediate
Can extension functions access private members of the class they extend?No, extension functions cannot access private or protected members of the class. They work like regular functions with the receiver object passed in, so only public members are accessible.
Click to reveal answer
intermediate
What happens if an extension function has the same signature as a member function?
The member function always wins. The extension function is ignored when calling on an instance of the class.
Click to reveal answer
intermediate
Write an extension property for List<Int> that returns the sum of all elements.
You can write:
val List<Int>.sumOfElements: Int get() = this.sum()This adds a read-only property to List<Int>.
Click to reveal answer
How do you call an extension function on a String named 'greet'?
✗ Incorrect
Extension functions are called like normal member functions on the object.
Can extension functions modify the original object they extend?
✗ Incorrect
Extension functions can modify the object if it is mutable, like a MutableList, but they cannot access private fields.
What keyword is used to declare an extension function in Kotlin?
✗ Incorrect
Extension functions are declared with the fun keyword, followed by the receiver type.
If a class has a member function and an extension function with the same name and parameters, which one is called?
✗ Incorrect
Member functions have higher priority than extension functions.
Which of these is a valid extension property declaration for Int?
✗ Incorrect
Extension properties must be declared with val or var and use a getter; var is not allowed without backing field.
Explain what extension functions are and how they help when working with built-in types in Kotlin.
Think about how you can add new abilities to existing classes.
You got /3 concepts.
Describe the difference between member functions and extension functions when they have the same name.
Consider what happens when Kotlin looks for a function to call.
You got /3 concepts.