From de4b0a4601e3b01ebcf93aca75090a649edde445 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Tue, 20 Dec 2011 17:27:22 +0000 Subject: [PATCH] added Alex's to(collection: Collection) helper method and simple 1 liners for toList / toLinkedList / toSet etc --- stdlib/ktSrc/JavaUtil.kt | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/stdlib/ktSrc/JavaUtil.kt b/stdlib/ktSrc/JavaUtil.kt index a96ac23b357..46cbda926e0 100644 --- a/stdlib/ktSrc/JavaUtil.kt +++ b/stdlib/ktSrc/JavaUtil.kt @@ -123,17 +123,22 @@ inline fun java.util.Collection.map(result: Collection = ArrayList< return result } -inline fun > java.lang.Iterable.toSortedList() : List { - val answer = this.toList() - answer.sort() - return answer + +inline fun > java.lang.Iterable.to(result: C) : C { + for (elem in this) + result.add(elem) + return result } -inline fun > java.lang.Iterable.toSortedList(comparator: java.util.Comparator) : List { - val answer = this.toList() - answer.sort(comparator) - return answer -} +inline fun java.lang.Iterable.toLinkedList() : LinkedList = this.to(LinkedList()) + +inline fun java.lang.Iterable.toList() : List = this.to(ArrayList()) + +inline fun java.lang.Iterable.toSet() : Set = this.to(HashSet()) + +inline fun > java.lang.Iterable.toSortedList() : List = toList().sort() + +inline fun > java.lang.Iterable.toSortedList(comparator: java.util.Comparator) : List = toList().sort(comparator) /** TODO figure out necessary variance/generics ninja stuff... :) @@ -144,17 +149,6 @@ inline fun java.lang.Iterable.toSortedList(transform: fun(T) : java.la } */ -inline fun java.lang.Iterable.toList() : List { - if (this is List) - return this - else { - val list = ArrayList() - for (elem in this) - list.add(elem) - return list - } -} - inline fun java.util.Collection.toArray() : Array { val answer = Array(this.size) var idx = 0 @@ -166,12 +160,14 @@ inline fun java.util.Collection.toArray() : Array { // List APIs -inline fun > List.sort() : Unit { +inline fun > List.sort() : List { Collections.sort(this) + return this } -inline fun > List.sort(comparator: java.util.Comparator) : Unit { +inline fun > List.sort(comparator: java.util.Comparator) : List { Collections.sort(this, comparator) + return this } /**