Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use plus, minus, times functions instead of using the operators in Kotlin?

Tags:

kotlin

I cannot think of a case where using the Kotlin built-in plus, minus, times etc. functions would return a different result from just using the corresponding operators (+, -, *). Why would you ever want to use these functions in your Kotlin code?

like image 396
notReallyDev Avatar asked Dec 23 '22 17:12

notReallyDev


1 Answers

Just in case you aren't aware, these are operator overloads. The named functions are how the operators' functionality is defined.

There is a case for using the named versions. The function calls don't pay attention to operator precedence and are evaluated sequentially if you chain them.

val x = 1
val y = 2
val z = 3

println(x + y * z)          // equivalent to 1 + (2 * 3) -> 7
println(x.plus(y).times(z)) // equivalent to (1 + 2) * 3 -> 9

This could be clearer than using the operators if you have a lot of nested parentheses, depending on the context of the type of math you're doing.

result = ((x - 7) * y - z) * 10

// vs

result = x.minus(7).times(y).minus(z).times(10)

It's not really applicable for basic algebra like this, but you might have classes with operator overloads where the logic can be more easily reasoned through with the sequential approach.

like image 86
Tenfour04 Avatar answered May 23 '23 08:05

Tenfour04