From 27ece9c76513a399fbddc85ee66df49f17e8c982 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Wed, 29 Feb 2012 09:51:22 +0000 Subject: [PATCH] split the filter method into filter(predicate) and filterTo(result, predicate) for easier completion & avoid confusion - seems 2 methods is better than the default arguments approach --- stdlib/ktSrc/Filter.kt | 11 ----------- stdlib/ktSrc/JavaIterables.kt | 12 +++++++++--- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/stdlib/ktSrc/Filter.kt b/stdlib/ktSrc/Filter.kt index bf458ae0fb8..8c31626d436 100644 --- a/stdlib/ktSrc/Filter.kt +++ b/stdlib/ktSrc/Filter.kt @@ -8,17 +8,6 @@ Filters given iterator */ inline fun java.util.Iterator.filter(f: (T)-> Boolean) : java.util.Iterator = FilterIterator(this, f) -/* -Adds filtered elements in to given container -*/ -inline fun > java.lang.Iterable.filterTo(var container: U, filter: (T)->Boolean) : U { - for(element in this) { - if(filter(element)) - container.add(element) - } - return container -} - /* Create iterator filtering given java.lang.Iterable */ diff --git a/stdlib/ktSrc/JavaIterables.kt b/stdlib/ktSrc/JavaIterables.kt index 9a63529c57c..c8ac5b970ab 100644 --- a/stdlib/ktSrc/JavaIterables.kt +++ b/stdlib/ktSrc/JavaIterables.kt @@ -41,8 +41,11 @@ inline fun java.lang.Iterable.find(predicate: (T)-> Boolean) : T? { return null } -/** Returns a new collection containing all elements in this collection which match the given predicate */ -inline fun java.lang.Iterable.filter(result: Collection = ArrayList(), predicate: (T)-> Boolean) : Collection { +/** Returns a new List containing all elements in this collection which match the given predicate */ +inline fun java.lang.Iterable.filter(predicate: (T)-> Boolean) : Collection = filterTo(java.util.ArrayList(), predicate) + +/** Filters all elements in this collection which match the given predicate into the given result collection */ +inline fun > java.lang.Iterable.filterTo(result: C, predicate: (T)-> Boolean) : C { for (elem in this) { if (predicate(elem)) result.add(elem) @@ -51,7 +54,10 @@ inline fun java.lang.Iterable.filter(result: Collection = ArrayList } /** Returns a new collection containing all elements in this collection which do not match the given predicate */ -inline fun java.lang.Iterable.filterNot(result: Collection = ArrayList(), predicate: (T)-> Boolean) : Collection { +inline fun java.lang.Iterable.filterNot(predicate: (T)-> Boolean) : Collection = filterNotTo(ArrayList(), predicate) + +/** Returns a new collection containing all elements in this collection which do not match the given predicate */ +inline fun > java.lang.Iterable.filterNotTo(result: C, predicate: (T)-> Boolean) : C { for (elem in this) { if (!predicate(elem)) result.add(elem)