Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Var recalculation after content change

I just started learning Kotlin and could not get one thing:

I have a variable that is based on some other variables (for example "A" and "B"). Is there an easy way to recalculate the resulted variable after i change var "A" or "B"?
As i understood, i can just repeat the code for "result" again, but is there an easier way? i think in some cases the code could be quite long…

Example is below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var valueA = 9
var valueB = 10
var result = valueA*valueB
println(result)

valueA = 15

"A" is changed, but if i write "println(result)" right now, var "result" will not be recalculated and will stay = 90

result = valueA*valueB
println(result)

only after i write the same code for "result" again, the output is recalculated

>Solution :

That’s how variables work. When you store something in them it will be how you put it in at the moment. If you want a dynamic result use a function instead:

fun result() = valueA * valueB

and then print like

println(result())

If they are class variables (properties) you actually can use variables but then you need to define it with a getter like this for example:

val result get() = valueA * valueB
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading