0
0
Kotlinprogramming~5 mins

Extension function syntax in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aextension fun Int.double() = this * 2
Bfun double(Int) = Int * 2
Cfun Int.double() = this * 2
Dfun double() Int = this * 2
Can extension functions override existing member functions of a class?
ANo, they cannot override member functions.
BOnly for open classes.
COnly if marked with override keyword.
DYes, they replace the member functions.
What does the this keyword refer to inside an extension function?
AThe caller of the function.
BThe extension function itself.
CThe global object.
DThe class being extended instance.
Which of these is NOT true about Kotlin extension functions?
AThey can access private members of the class.
BThey are declared with fun keyword.
CThey can add new functions to existing classes.
DThey do not modify the original class.
How do you call an extension function greet on a String object "World"?
Agreet("World")
B"World".greet()
CString.greet("World")
Dcall greet on "World"
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.