Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Var recalculation after content change

Tags:

kotlin

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:

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

like image 354
Илья Мисников Avatar asked Sep 12 '25 19:09

Илья Мисников


1 Answers

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
like image 173
Ivo Beckers Avatar answered Sep 14 '25 10:09

Ivo Beckers