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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With