我写运算符
private fun method() {
operator fun Float.rangeTo(other: Int) {
(this.toInt()..other).forEach { print(it) }
}
0f..4
}
这很好用,即打印
01234
但是当我用
float
替换Int
时,它不再起作用,即不打印01234
private fun method() {
operator fun Int.rangeTo(other: Int) {
(this..other).forEach { print(it) }
}
0..4
}
我错过了什么?我该如何运作?
最佳答案
如果您在IntelliJ中查看此代码,则会在rangeTo
函数上以警告的形式得到答案:
Extension is shadowed by a member: public final operator fun rangeTo(other: Int): IntRange
扩展不能覆盖类型已经具有的方法,并且由于
Int
具有非扩展的rangeTo(Int)
方法,因此0..4
语法将始终调用该方法。如果考虑一下,当您写下this..other
时,您实际上是在利用这个事实,因为这是对内置rangeTo
运算符的调用,而不是对您自己的扩展函数的递归调用。它使用
Float
的原因是它没有自己的成员rangeTo(Int)
方法。
关于kotlin - 覆盖运算符Int RangeTo不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51286973/