Is multiplication always commutative in Kotlin π€?
What is commutative property?
To quote from Wikipedia,
A binary operation is commutative if changing the order of the operands does not change the result.
Of course, it is mentioned In Mathematics
, but in our case, it is for programming
.
An operator is commutative if a operator b = b operator a
Examples5 * 2 = 2 * 5 = 10
3 + 4 = 4 + 3 = 7
Kotlin
In kotlin, we can observe that
For the same data types,
val x = 5 * 2
and val x = 2 * 5
would be the same. (Multiplication of Int)val x = 5.0 * 2.0
and val x = 2.0 * 5.0
are also the same (Multiplication of Double)
For different data types,
val x = 2 * 3.0
and val x = 3.0 * 2
are also the same.
(Multiplication of Int and Double and vice-versa)
This shows multiplication is commutative for the above cases.
But is it always the case?
Non-commutative multiplication in Kotlin
By commutative property, if Num(5.0) * 2
is valid 2 * Num(5.0)
should also be valid and have equal value.
But we would get the below error.
This is because Num
is a user-defined class that has the times
operator to accept Int
parameter.
So, unless there is a times
operator in Int
to accept Num
parameter, multiplication of Num
and Int
will not be commutative.
For Commutative multiplication in Kotlin
- If both operands are of the same data type and multiplication is a valid operation, then it would be commutative.
- If both operands are of different data types, both need to have an
times()
operation that accepts the other data type to be commutative.
Practical Use
We saw what is commutative operation in Kotlin, when the operation would be commutative and when it would not be.
But what is the practical use of all this information?
This is one such use case I am aware of, there might be other use cases as well.
In Android Jetpack Compose we have a Dp
class for dimensions. In that
Dp
has operators for Int, Float and Double
. But Int
, Float
and Double
should always be the second operand for the operation to be valid.
Note: Though we have discussed only in terms of multiplication, it is applicable for other operators as well.
Please comment with your valuable feedback. It would help me to improvise.
Kindly πππ if this was useful.
Please follow if you would like to see more content related to Android Jetpack Compose.