3

这是我在做 Koan N28 时遇到的:

class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {

    private operator fun MyDate.inc() : MyDate {
        return this.nextDay()
    }

    override fun iterator(): Iterator<MyDate> {
        return object : Iterator<MyDate> {
            private var point = start

            override fun hasNext(): Boolean {
                return point <= endInclusive
            }

            override fun next(): MyDate {
                return if (hasNext()) point++ else throw NoSuchElementException()
            }


        }
    }
}

但是,编译器在该operator位置大喊大叫,说'operator' modifier is inapplicable on this function: receiver must be a supertype of the return type. 为了让代码编译,我必须将扩展函数移到顶层。但是,如果我MyDate.unaryPlus()在同一个地方重载,代码会编译。

4

0 回答 0