首页 > 解决方案 > 是否可以编写“双重”扩展方法?

问题描述

在 Kotlin 中,可以编写

class A {
  fun B.foo()
}

然后例如写with (myA) { myB.foo() }

是否可以将其作为扩展方法写在 上A,而不是?我的用例是写

with (java.math.RoundingMode.CEILING) { 1 / 2 }

我想返回1,重点是我想operator fun Int.div(Int)添加RoundingMode

标签: kotlin

解决方案


不,这是不可能的。operator div需要有Int作为接收器。

您不能也添加RoundingMode为接收器,因为只能有单个功能接收器。

但是,您可以做的是Pair<RoundingMode, Int>用作接收器:

operator fun Pair<RoundingMode, Int>.div(i: Int): BigDecimal =
        BigDecimal.valueOf(second.toLong()).divide(BigDecimal.valueOf(i.toLong()), first)

with(RoundingMode.CEILING) {
    println((this to 1) / 2) // => 1
}

推荐阅读