kotlin - 覆盖运算符Int RangeTo不起作用

标签 kotlin

我写运算符

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/

相关文章:

kotlin - Micronaut - 在 Controller 中绑定(bind)获取参数对象

android - 如何声明与 lambda 一起使用的接口(interface)?

java - Kotlin 或 Java 中恒定时间复杂度 O(1) 的 Concat 链表

java - 认证和签名后锁定 PDF 文件

kotlin 中的 Android ViewModelProviderFactory

android - 房间数据库在 macbook pro m1 中不起作用

java - Gradle 不会导入 bintray 依赖项,但不会抛出任何错误

multithreading - 使用多线程时Kotlin无法解析的引用

用于绑定(bind)通用 View 的 Android Kotlin 扩展

android - 圆形进度指示器忽略宽度/高度属性并且不缩放