kotlin - 是否可以编写“双重”扩展方法?
问题描述
在 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
。
解决方案
不,这是不可能的。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
}
推荐阅读
- node.js - 对话流中的网页抓取
- r-markdown - knitr 不识别已安装的包,但单独运行块没有问题
- python - Pandas - Get a row of data when looping through groupBy results
- r - 根据行中的不同数据创建新数据框
- docker - 如何访问 Docker 容器内的根文件夹
- java - Hibernate:仅允许具有给定属性的实体加入 OneToMany 关联
- javascript - 如果没有发出任何内容,take(1).subscribe()-subscription 会永远存在吗?
- f# - 为什么我在 if 语句中收到 bool 的错误消息
- drupal-modules - 清除缓存后 Drupal 8 自定义块输出变为空白
- java - 如何在一个类中设置变量并在另一个类中获取它