Extension functions are really-really helpful while writing code in Kotlin. You don’t have to extend the class but you can add the functionality to even a final (non-open) class which will be resolved statically but how about extension properties.
This blog was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-extension-property/ and reposted on Medium on 13th Sept 2020.
A very interesting question asked to me during an interview or even a general situation where we need to add a property (variable) to an existing class without extending it.
Is it even possible?
Can we add a property/variable as an extension to an existing class?
According to the theory of extension functions, this is not possible since you can only add the extension functions but not properties, but there is a workaround which can solve the purpose.
Let’s try to understand that workaround first and then talk about the limitations.
Say there is a class name
Temperature which only has one property
tempInCelsius which it takes as a parameter in the constructor.
class Temperature(var tempInCelsius: Float)
Now I want to add one more property
tempInFahrenheit which will be holding the same value of temperature but in Fahrenheit.
I actually can’t add a property for the same but I can add getter and setter which are nothing but the extension functions to the same.
var Temperature.tempInFahrenheit: Float
get() = (tempInCelsius * 9 / 5) + 32
tempInCelsius = (value - 32) * 5 / 9