How to identify a new operator in Kotlin?

Is it possible to define a general exponentiation operator that can be related as follows:

> 10^3         // 1000
> 2.71^2       // 7.3441
> 3.14^(-3.14) // 0.027..

In accordance with the documents, you can extend classes using infix functions:

// Define extension to Int
infix fun Int.exp(exponent: Int): Int {
...
}

But they do not allow characters like ^

+10
source share
3 answers

Unfortunately, you cannot define new operators; there is only a predefined set of those that can be overloaded. Some operators can be added to this set later, for this there is a problem in the Kotlin problem tracker.

, infix , ( ):

infix fun Int.'^'(exponent: Int): Int = ... 

:

5 '^' 3

, infix , ,

1 + 1 '^' 3 == 8
+22

. Kotlin , . ^ ( AFAIK, ).

0

. Android Studio ^ . , v (^ ). ? , , Thons pow .

inline infix fun Double.v(exponent: Int): Double = this.pow(exponent)
inline infix fun Double.v(exponent: Long): Double = this.pow(exponent.toDouble())
inline infix fun Double.v(exponent: Double): Double = this.pow(exponent)
inline infix fun Int.v(exponent: Int): Double = this.toDouble().pow(exponent)
inline infix fun Int.v(exponent: Long): 
      Double = this.toDouble().pow(exponent.toDouble())
inline infix fun Int.v(exponent: Double): Double = this.toDouble().pow(exponent)
inline infix fun Long.v(exponent: Int): Double = this.toDouble().pow(exponent)
inline infix fun Long.v(exponent: Long): 
      Double = this.toDouble().pow(exponent.toDouble())
inline infix fun Long.v(exponent: Double): 
      Double = this.toDouble().pow(exponent)

inline use does not create additional load at runtime, even inside heavier loops.

Unfortunately, a damaged operator priority forces you to bracket the power-on operation. And the compiler makes you flank spaces.

In the end, what gives a better look?

It?

var k=2  
...
println((k v 5)+3)

Or that?

var k=2
 ... 
println(k.toDouble().pow(5) + 3)

I vote for the first option!

0
source

All Articles