Is it possible to define a generic exponentiation operator that can be interfaced like this:
> 10^3 // 1000
> 2.71^2 // 7.3441
> 3.14^(-3.14) // 0.027..
According to the docs it's possible to extend classes with infix functions:
// Define extension to Int
infix fun Int.exp(exponent: Int): Int {
...
}
But they don't allow symbols like ^
The elvis operator in Kotlin is used for null safety. x = a ?: b. In the above code, x will be assigned the value of a if a is not null and b if a is null . The equivalent kotlin code without using the elvis operator is below: x = if(a == null) b else a.
The strange += operator in Kotlinintroduce a mutable structure of the class for the plusAssign operator which means its internal data can be edited anywhere.
Unfortunately, you cannot define new operators, there's only a predefined set of those that can be overloaded. Some operators might be added to this set later, there's an open issue for that in the Kotlin issue tracker.
However, you can use backticked names to define infix
extension functions which look like operators (much less pretty though):
infix fun Int.`^`(exponent: Int): Int = ...
Usage:
5 `^` 3
Note that infix
functions have precedence lower than that of operators, thus
1 + 1 `^` 3 == 8
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