Modify List.get behavior in Kotlin -


in kotlin, what's idiomatic way modify behavior of list.get such calling get(-1) returns last element in list?

i tried extension:

operator fun <t> list<t>.get(index: int): t {     return this[if (index < 0) size + index else index] } 

but didn't behave desired, , got warning

scratch.kts:3:26: warning: extension shadowed member: public abstract operator fun get(index: int): t operator fun <t> list<t>.get(index: int): t {                          ^ 

since can't hide member method extension method, option work have subclass overrides functionality in way describe.

class negativelyindexablelist<t> : arraylist<t>() {   override fun get(index: int): t =     if (index < 0) super.get(size + index) else super.get(index) } 

however should consider future users of code. obfuscate what's going on here. meaning of list[index] changes based on value of index, , won't obvious in places list , / or index not known in advance. consider trivial example:

fun getvaluefromafewdaysago(timeline: list<day>, today: int, daysago: int) =   timeline[today - daysago] 

if today 2 , daysago 7, method either throw exception (if timeline regular list) or return future (if timeline negativelyindexablelist).

if have have feature, consider not conflating get. add new method:

fun getfromend(index: int) = asreversed()[index] 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -