是否可以定义一个通用的求幂运算符,其接口如下:

> 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 {
...
}

但他们不允许像^这样的符号

推荐答案

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

Kotlin相关问答推荐

Jetpack Compose中的数字 Select 器问题

只能在元素区域中点击的Jetpack Compose列

如何在Kotlin中为接受varargs的函数添加带有默认值的新参数?

如何让 LocalDateTime.parse 拒绝 24:00 时间

Kotlin中用于调用常量名称的枚举类方法之间的区别

在 kotlin 中重载函数时,我在一些非常基本的代码上不断收到类型不匹配

Saripaar formvalidation 在 kotlin 中第二次不起作用

为什么 Kotlin 需要函数引用语法?

如何创建 Kotlin DSL - DSL 语法 Kotlin

在粘贴时将 java 转换为 kotlin

Kotlin 静态函数:伴生对象,@JvmStatic @JvmField

Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda }

将 @Component.Builder 与构造函数参数一起使用

@uncheckedVariance 在 Kotlin 中?

如何暂停kotlin coroutine直到收到通知

Android EditText 协程go 抖操作符,如 RxJava

Failure delivering result on activity result

如何在kotlin用mockito模仿lambda

Kotlin中的嵌套let块

是否可以在不使用class的情况下将 Mockito 与 Kotlin 一起使用?