Recall & Review
beginner
What is an extension function in Kotlin?
An extension function lets you add a new function to an existing class without changing its source code or inheriting from it.Click to reveal answer
beginner
How do you declare an extension function for the String class named <code>shout</code> that returns the string in uppercase?You write <code>fun String.shout(): String { return this.uppercase() }</code>. The <code>String</code> before the dot is the class being extended.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 only work with the public API.
Click to reveal answer
beginner
What keyword is used to define an extension function in Kotlin?
The keyword <code>fun</code> is used, followed by the class name, a dot, and the function name.Click to reveal answer
beginner
How do you call an extension function on an object?
You call it just like a normal function on the object, for example:
"hello".shout().Click to reveal answer
Which of the following is the correct syntax to declare an extension function
double for Int that returns the number multiplied by 2?✗ Incorrect
The correct syntax is fun ClassName.functionName() = ... so fun Int.double() = this * 2 is right.
Can extension functions override existing member functions of a class?
✗ Incorrect
Extension functions do not override member functions; if a member function exists, it is called instead.
What does the
this keyword refer to inside an extension function?✗ Incorrect
Inside an extension function, this refers to the instance of the class being extended.
Which of these is NOT true about Kotlin extension functions?
✗ Incorrect
Extension functions cannot access private or protected members of the class.
How do you call an extension function
greet on a String object "World"?✗ Incorrect
Extension functions are called like normal functions on the object: "World".greet()
Explain how to write and use an extension function in Kotlin.
Think about adding a new function to a class without changing it.
You got /4 concepts.
What are the limitations of Kotlin extension functions compared to member functions?
Consider what extension functions cannot do inside the class.
You got /3 concepts.