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?

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
set(value) {
tempInCelsius = (value - 32) * 5 / 9

Please continue reading at https://agrawalsuneet.github.io/blogs/kotlin-extension-property/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store