Fix functions List<T>.sort() and add sort functions for java.lang.Iterables.

See Problem 3 at https://github.com/JetBrains/kotlin/pull/78#issuecomment-6533534
This commit is contained in:
Alexander Zolotov
2012-06-26 00:36:24 +04:00
parent 1cc7ab6b8d
commit 34f485e45a
3 changed files with 26 additions and 19 deletions
@@ -105,6 +105,18 @@ public fun <T> java.lang.Iterable<T>.withIndices() : java.lang.Iterable<#(Int, T
}
}
public inline fun <in T: java.lang.Comparable<T>> java.lang.Iterable<T>.sort() : List<T> {
val list = toList()
java.util.Collections.sort(list)
return list
}
public inline fun <in T> java.lang.Iterable<T>.sort(comparator: java.util.Comparator<T>) : List<T> {
val list = toList()
java.util.Collections.sort(list, comparator)
return list
}
private class NumberedIterator<TT>(private val sourceIterator : java.util.Iterator<TT>) : java.util.Iterator<#(Int, TT)> {
private var nextIndex = 0
-11
View File
@@ -40,17 +40,6 @@ public inline fun <in T: java.lang.Comparable<T>> java.lang.Iterable<T>.toSorted
// List APIs
public inline fun <in T: java.lang.Comparable<T>> List<T>.sort() : List<T> {
Collections.sort(this)
return this
}
public inline fun <in T> List<T>.sort(comparator: java.util.Comparator<T>) : List<T> {
Collections.sort(this, comparator)
return this
}
/** Returns the List if its not null otherwise returns the empty list */
public inline fun <T> java.util.List<T>?.orEmpty() : java.util.List<T>
= if (this != null) this else Collections.emptyList<T>() as java.util.List<T>
+14 -8
View File
@@ -337,15 +337,21 @@ class CollectionTest {
expect(arrayList(2, 3, 1)) { iterable }
}
test fun sort() {
val coll: List<String> = arrayList("foo", "bar", "abc")
// TODO fixme
// Some sort of in/out variance thing - or an issue with Java interop?
//coll.sort()
test fun sortFunctionShouldReturnSortedCopyForList() {
// TODO fixme Some sort of in/out variance thing - or an issue with Java interop?
todo {
assertEquals(3, coll.size)
assertEquals(arrayList("abc", "bar", "foo"), coll)
// val list : List<Int> = arrayList<Int>(2, 3, 1)
// expect(arrayList(1, 2, 3)) { list.sort() }
// expect(arrayList(2, 3, 1)) { list }
}
}
test fun sortFunctionShouldReturnSortedCopyForIterable() {
// TODO fixme Some sort of in/out variance thing - or an issue with Java interop?
todo {
// val list : java.lang.Iterable<Int> = arrayList(2, 3, 1)
// expect(arrayList(1, 2, 3)) { list.sort() }
// expect(arrayList(2, 3, 1)) { list }
}
}