0
0
Kotlinprogramming~5 mins

Extension properties in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an extension property in Kotlin?
An extension property allows you to add a new property to an existing class without modifying its source code. It behaves like a regular property but is defined outside the class.
Click to reveal answer
intermediate
Can extension properties have backing fields in Kotlin?
No, extension properties cannot have backing fields. They must be defined with a getter (and optionally a setter) that computes the value.
Click to reveal answer
beginner
How do you define a read-only extension property for the String class that returns the first character?
You define it like this: <br>
val String.firstChar: Char<br>    get() = this[0]
Click to reveal answer
intermediate
Why can't extension properties access private members of the class they extend?
Because extension properties are defined outside the class, they do not have access to the class's private members. They only use the public API.
Click to reveal answer
intermediate
What happens if you define an extension property with the same name as a member property?
The member property always takes precedence. The extension property will be ignored when accessed through an instance of the class.
Click to reveal answer
Which of the following is true about Kotlin extension properties?
AThey can have backing fields.
BThey can only have getters and setters without backing fields.
CThey can modify private members of the class.
DThey require modifying the original class source code.
How do you declare a read-only extension property named 'lastChar' for String?
Afun String.lastChar() = this.last()
Bval lastChar: String get() = this.last()
Cvar String.lastChar: Char = this.last()
Dval String.lastChar: Char get() = this.last()
If a class has a member property 'size' and you define an extension property 'size', which one is used when accessing 'size' on an instance?
AThe member property
BThe extension property
CBoth are used alternately
DIt causes a compile error
Can extension properties access private properties of the class they extend?
ANo, they cannot access private members
BOnly if declared in the same package
COnly if the class is open
DYes, always
What is the main benefit of using extension properties?
ATo access private members of a class
BTo override existing properties
CTo add new properties without changing the original class
DTo create new classes
Explain what extension properties are in Kotlin and how they differ from regular properties.
Think about how you add new properties without changing the original class.
You got /4 concepts.
    Describe the limitations of extension properties in Kotlin.
    Consider what extension properties cannot do compared to regular properties.
    You got /4 concepts.