Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define new operator in Kotlin?

Tags:

kotlin

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 ^

like image 329
TomTom Avatar asked Jun 04 '16 13:06

TomTom


People also ask

What does ?: Means in Kotlin?

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.

Is there a += in Kotlin?

The strange += operator in Kotlinintroduce a mutable structure of the class for the plusAssign operator which means its internal data can be edited anywhere.


1 Answers

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
like image 65
hotkey Avatar answered Oct 14 '22 11:10

hotkey