修改Kotlin中的List.get行为

在Kotlin中,修改List.get行为的惯用方式是什么?调用get(-1)返回列表中的最后一个元素?

我尝试了一个扩展:

 operator fun  List.get(index: Int): T { return this[if (index < 0) size + index else index] } 

但它没有按照要求行事,我得到了警告

 scratch.kts:3:26: warning: extension is shadowed by a member: public abstract operator fun get(index: Int): T operator fun  List.get(index: Int): T { ^ 

既然你不能用一个扩展方法隐藏成员方法,唯一可行的方法就是拥有一个按你描述的方式覆盖function的子类。

 class NegativelyIndexableList : ArrayList() { override fun get(index: Int): T = if (index < 0) super.get(size + index) else super.get(index) } 

不过,你应该考虑这个代码的未来用户。 它混淆了这里发生的事情。 list[index]的含义是根据list[index]的值而变化的,这在listindex不被预先知道的地方是不明显的。 考虑这个微不足道的例子:

 fun getValueFromAFewDaysAgo(timeline: List, today: Int, daysAgo: Int) = timeline[today - daysAgo] 

如果today是2, daysAgo是7,那么这个方法将会抛出一个exception(如果timeline是常规列表),或者返回将来的东西(如果timelineNegativelyIndexableList )。

如果你真的必须有这个function,那就考虑不要把它与get搞混了。 添加一个新的方法:

 fun getFromEnd(index: Int) = asReversed()[index]