Extension properties
In this section, we will first understand what extension properties are, and then we will move on to learn where these properties can be used. As we already know, properties in Kotlin are defined by their accessors (getter and setter):
class User(val name: String, val surname: String) { val fullName: String get() = "$name $surname" }
We can also define the extension property. The only limitation is that this property can't have a backing field. The reason for this is that extension can't store state, so there is no good place to store this field. Here is an example of an extension property definition for TextView
:
val TextView.trimmedText: String get() = text.toString().trim() // Usage textView.trimmedText
As with extension functions, the preceding implementation will be compiled as an accessor function with a receiver on the first parameter. Here is the simplified result in Java:
public class AndroidUtilsKt { ...