0
0
Kotlinprogramming

Extensions on built-in types 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 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'?
Agreet("Hello")
B"Hello".greet()
CString.greet("Hello")
Dcall greet on "Hello"
Can extension functions modify the original object they extend?
AOnly if the object is mutable
BNo, they cannot modify the original object
CYes, they can change private fields
DYes, but only for built-in types
What keyword is used to declare an extension function in Kotlin?
Aoverride
Bextend
Cfun
Dextension
If a class has a member function and an extension function with the same name and parameters, which one is called?
ACompilation error
BExtension function
CBoth are called
DMember function
Which of these is a valid extension property declaration for Int?
Aval Int.isEven get() = this % 2 == 0
Bvar Int.isEven = this % 2 == 0
Cfun Int.isEven() = this % 2 == 0
Dproperty Int.isEven get() = this % 2 == 0
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.