# Bug in Array.sort() extension function

**URL:** <https://discuss.kotlinlang.org/t/bug-in-array-sort-extension-function/567>\
**Category:** Uncategorized\
**Created:** [June 11, 2014, 9:40pm UTC](https://discuss.kotlinlang.org/t/bug-in-array-sort-extension-function/567 "2014-06-11T21:40:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kburjorj](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/kburjorj/32/1553_2.png) [@kburjorj](https://discuss.kotlinlang.org/u/kburjorj)\
**Post date:** [June 11, 2014, 9:40pm UTC](https://discuss.kotlinlang.org/t/bug-in-array-sort-extension-function/567/1 "2014-06-11T21:40:50Z")

</div>

On [http://kotlin-demo.jetbrains.com/](http://kotlin-demo.jetbrains.com/)

fun main(args : Array\<String\>) {  
&nbsp;&nbsp;val nums = array (5,4,3,2,1)  
&nbsp;&nbsp;nums.sort()  
&nbsp;&nbsp;nums forEach {print (it)}  
}

produces output

Generated classfiles: \_DefaultPackage.class \_DefaultPackage-dummy-b9f6f59e.class \_DefaultPackage$main$1.class 23451

The root cause seems to be that the the default value of toIndex in the following extension function assumes an end-inclusive range (probably because ranges are currently end-inclusive in Kotlin). However, ranges are end-exclusive in Java.

/\*\* \* Sorts array or range in array inplace \*/ public fun \<T\> Array\<out T\>.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { &nbsp;&nbsp;Arrays.sort(this, fromIndex, toIndex) }

I think one can count this bug as a point in favour of making end-exclusivity the convention in Kotlin as I’ve argued here: [http://devnet.jetbrains.com/thread/455071?tstart=0](http://devnet.jetbrains.com/thread/455071?tstart=0). An end-inclusive Kotlin interoperating with end-exclusive Java seems like it would be prone to errors.

---

<div class="post-metadata">

**Author:** ![abreslav](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/abreslav/32/8279_2.png) [@abreslav](https://discuss.kotlinlang.org/u/abreslav)\
**Post date:** [June 12, 2014, 8:47am UTC](https://discuss.kotlinlang.org/t/bug-in-array-sort-extension-function/567/2 "2014-06-12T08:47:00Z")

</div>

Already fixed in master.

You are right: the fact that Java’s libraries have end-exclusive conventions is a point for having end-exclusivity in Kotlin as well.
