New stdlib generators

This commit is contained in:
Ilya Ryzhenkov
2014-03-18 13:45:31 +04:00
committed by Andrey Breslav
parent 0980f5e40a
commit e37d8174c3
109 changed files with 13317 additions and 7735 deletions
File diff suppressed because it is too large Load Diff
+54 -457
View File
@@ -8,531 +8,128 @@ package kotlin
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
* Returns true if the array is empty
*/
public inline fun <T> Array<out T>.all(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
public fun <T> Array<out T>.isEmpty() : Boolean {
return size == 0
}
/**
* Returns *true* if any elements match the given *predicate*
* Returns true if the array is empty
*/
public inline fun <T> Array<out T>.any(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
public fun BooleanArray.isEmpty() : Boolean {
return size == 0
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
* Returns true if the array is empty
*/
public fun <T> Array<out T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
public fun ByteArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns the number of elements which match the given *predicate*
* Returns true if the array is empty
*/
public inline fun <T> Array<out T>.count(predicate: (T) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
public fun CharArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns a list containing everything but the first *n* elements
* Returns true if the array is empty
*/
public fun <T> Array<out T>.drop(n: Int) : List<T> {
return dropWhile(countTo(n))
public fun DoubleArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
* Returns true if the array is empty
*/
public inline fun <T> Array<out T>.dropWhile(predicate: (T) -> Boolean) : List<T> {
return dropWhileTo(ArrayList<T>(), predicate)
public fun FloatArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
* Returns true if the array is empty
*/
public inline fun <T, L: MutableList<in T>> Array<out T>.dropWhileTo(result: L, predicate: (T) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
public fun IntArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns a list containing all elements which match the given *predicate*
* Returns true if the array is empty
*/
public inline fun <T> Array<out T>.filter(predicate: (T) -> Boolean) : List<T> {
return filterTo(ArrayList<T>(), predicate)
public fun LongArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns a list containing all elements which do not match the given *predicate*
* Returns true if the array is empty
*/
public inline fun <T> Array<out T>.filterNot(predicate: (T) -> Boolean) : List<T> {
return filterNotTo(ArrayList<T>(), predicate)
public fun ShortArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns a list containing all the non-*null* elements
* Returns true if the array is not empty
*/
public fun <T:Any> Array<out T?>.filterNotNull() : List<T> {
return filterNotNullTo<T, ArrayList<T>>(ArrayList<T>())
public fun <T> Array<out T>.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Filters all non-*null* elements into the given list
* Returns true if the array is not empty
*/
public fun <T:Any, C: MutableCollection<in T>> Array<out T?>.filterNotNullTo(result: C) : C {
for (element in this) if (element != null) result.add(element)
return result
public fun BooleanArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Returns a list containing all elements which do not match the given *predicate*
* Returns true if the array is not empty
*/
public inline fun <T, C: MutableCollection<in T>> Array<out T>.filterNotTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
public fun ByteArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Filters all elements which match the given predicate into the given list
* Returns true if the array is not empty
*/
public inline fun <T, C: MutableCollection<in T>> Array<out T>.filterTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
public fun CharArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
* Returns true if the array is not empty
*/
public inline fun <T:Any> Array<out T>.find(predicate: (T) -> Boolean) : T? {
for (element in this) if (predicate(element)) return element
return null
public fun DoubleArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
* Returns true if the array is not empty
*/
public inline fun <T, R> Array<out T>.flatMap(transform: (T)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
public fun FloatArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
* Returns true if the array is not empty
*/
public inline fun <T, R, C: MutableCollection<in R>> Array<out T>.flatMapTo(result: C, transform: (T) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
public fun IntArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
* Returns true if the array is not empty
*/
public inline fun <T, R> Array<out T>.fold(initial: R, operation: (R, T) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
public fun LongArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
* Returns true if the array is not empty
*/
public inline fun <T, R> Array<out T>.foldRight(initial: R, operation: (T, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun <T> Array<out T>.forEach(operation: (T) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <T, K> Array<out T>.groupBy(toKey: (T) -> K) : Map<K, List<T>> {
return groupByTo(HashMap<K, MutableList<T>>(), toKey)
}
public inline fun <T, K> Array<out T>.groupByTo(result: MutableMap<K, MutableList<T>>, toKey: (T) -> K) : Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun <T> Array<out T>.indexOf(item: T) : Int {
if (item == null) {
for (i in indices) {
if (this[i] == null) {
return i
}
}
} else {
for (i in indices) {
if (item == this[i]) {
return i
}
}
}
return -1
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Array<out T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <T, R> Array<out T>.map(transform : (T) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <T, R, C: MutableCollection<in R>> Array<out T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun <T: Comparable<T>> Array<out T>.max() : T? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>, T: Any> Array<out T>.maxBy(f: (T) -> R) : T? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun <T: Comparable<T>> Array<out T>.min() : T? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>, T: Any> Array<out T>.minBy(f: (T) -> R) : T? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun <T> Array<out T>.partition(predicate: (T) -> Boolean) : Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun <T> Array<out T>.plus(collection: Iterable<T>) : List<T> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun <T> Array<out T>.plus(element: T) : List<T> {
val answer = ArrayList<T>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun <T> Array<out T>.plus(iterator: Iterator<T>) : List<T> {
val answer = ArrayList<T>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun <T> Array<out T>.reduce(operation: (T, T) -> T) : T {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: T = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun <T> Array<out T>.reduceRight(operation: (T, T) -> T) : T {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> Array<out T?>.requireNoNulls() : Array<out T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this")
}
}
return this as Array<out T>
}
/**
* Reverses the order the elements into a list
*/
public fun <T> Array<out T>.reverse() : List<T> {
val list = toCollection(ArrayList<T>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <T, R: Comparable<R>> Array<out T>.sortBy(f: (T) -> R) : List<T> {
val sortedList = toCollection(ArrayList<T>())
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun <T> Array<out T>.take(n: Int) : List<T> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <T> Array<out T>.takeWhile(predicate: (T) -> Boolean) : List<T> {
return takeWhileTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <T, C: MutableCollection<in T>> Array<out T>.takeWhileTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <T, C: MutableCollection<in T>> Array<out T>.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun <T> Array<out T>.toLinkedList() : LinkedList<T> {
return toCollection(LinkedList<T>())
}
/**
* Copies all elements into a [[List]]
*/
public fun <T> Array<out T>.toList() : List<T> {
return toCollection(ArrayList<T>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun <T> Array<out T>.toSet() : Set<T> {
return toCollection(LinkedHashSet<T>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun <T> Array<out T>.toSortedSet() : SortedSet<T> {
return toCollection(TreeSet<T>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun <T> Array<out T>.withIndices() : Iterator<Pair<Int, T>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun Array<Byte>.sum() : Int {
return fold(0, {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Array<Short>.sum() : Int {
return fold(0, {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Array<Int>.sum() : Int {
return fold(0, {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Array<Long>.sum() : Long {
return fold(0.toLong(), {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Array<Float>.sum() : Float {
return fold(0.toFloat(), {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Array<Double>.sum() : Double {
return fold(0.0, {a,b -> a+b})
public fun ShortArray.isNotEmpty() : Boolean {
return !isEmpty()
}
@@ -1,447 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun BooleanArray.all(predicate: (Boolean) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun BooleanArray.any(predicate: (Boolean) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun BooleanArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun BooleanArray.count(predicate: (Boolean) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun BooleanArray.drop(n: Int) : List<Boolean> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun BooleanArray.dropWhile(predicate: (Boolean) -> Boolean) : List<Boolean> {
return dropWhileTo(ArrayList<Boolean>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Boolean>> BooleanArray.dropWhileTo(result: L, predicate: (Boolean) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun BooleanArray.filter(predicate: (Boolean) -> Boolean) : List<Boolean> {
return filterTo(ArrayList<Boolean>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun BooleanArray.filterNot(predicate: (Boolean) -> Boolean) : List<Boolean> {
return filterNotTo(ArrayList<Boolean>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Boolean>> BooleanArray.filterNotTo(result: C, predicate: (Boolean) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Boolean>> BooleanArray.filterTo(result: C, predicate: (Boolean) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun BooleanArray.find(predicate: (Boolean) -> Boolean) : Boolean? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> BooleanArray.flatMap(transform: (Boolean)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> BooleanArray.flatMapTo(result: C, transform: (Boolean) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> BooleanArray.fold(initial: R, operation: (R, Boolean) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> BooleanArray.foldRight(initial: R, operation: (Boolean, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun BooleanArray.forEach(operation: (Boolean) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> BooleanArray.groupBy(toKey: (Boolean) -> K) : Map<K, List<Boolean>> {
return groupByTo(HashMap<K, MutableList<Boolean>>(), toKey)
}
public inline fun <K> BooleanArray.groupByTo(result: MutableMap<K, MutableList<Boolean>>, toKey: (Boolean) -> K) : Map<K, MutableList<Boolean>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Boolean>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun BooleanArray.indexOf(item: Boolean) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun BooleanArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun BooleanArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun BooleanArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> BooleanArray.map(transform : (Boolean) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> BooleanArray.mapTo(result: C, transform : (Boolean) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> BooleanArray.maxBy(f: (Boolean) -> R) : Boolean? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> BooleanArray.minBy(f: (Boolean) -> R) : Boolean? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun BooleanArray.partition(predicate: (Boolean) -> Boolean) : Pair<List<Boolean>, List<Boolean>> {
val first = ArrayList<Boolean>()
val second = ArrayList<Boolean>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun BooleanArray.plus(collection: Iterable<Boolean>) : List<Boolean> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun BooleanArray.plus(element: Boolean) : List<Boolean> {
val answer = ArrayList<Boolean>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun BooleanArray.plus(iterator: Iterator<Boolean>) : List<Boolean> {
val answer = ArrayList<Boolean>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun BooleanArray.reduce(operation: (Boolean, Boolean) -> Boolean) : Boolean {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Boolean = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun BooleanArray.reduceRight(operation: (Boolean, Boolean) -> Boolean) : Boolean {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun BooleanArray.reverse() : List<Boolean> {
val list = toCollection(ArrayList<Boolean>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> BooleanArray.sortBy(f: (Boolean) -> R) : List<Boolean> {
val sortedList = toCollection(ArrayList<Boolean>())
val sortBy: Comparator<Boolean> = comparator<Boolean> {(x: Boolean, y: Boolean) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun BooleanArray.take(n: Int) : List<Boolean> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun BooleanArray.takeWhile(predicate: (Boolean) -> Boolean) : List<Boolean> {
return takeWhileTo(ArrayList<Boolean>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Boolean>> BooleanArray.takeWhileTo(result: C, predicate: (Boolean) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Boolean>> BooleanArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun BooleanArray.toLinkedList() : LinkedList<Boolean> {
return toCollection(LinkedList<Boolean>())
}
/**
* Copies all elements into a [[List]]
*/
public fun BooleanArray.toList() : List<Boolean> {
return toCollection(ArrayList<Boolean>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun BooleanArray.toSet() : Set<Boolean> {
return toCollection(LinkedHashSet<Boolean>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun BooleanArray.toSortedSet() : SortedSet<Boolean> {
return toCollection(TreeSet<Boolean>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun BooleanArray.withIndices() : Iterator<Pair<Int, Boolean>> {
return IndexIterator(iterator())
}
@@ -1,482 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun ByteArray.all(predicate: (Byte) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun ByteArray.any(predicate: (Byte) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ByteArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun ByteArray.count(predicate: (Byte) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun ByteArray.drop(n: Int) : List<Byte> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun ByteArray.dropWhile(predicate: (Byte) -> Boolean) : List<Byte> {
return dropWhileTo(ArrayList<Byte>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Byte>> ByteArray.dropWhileTo(result: L, predicate: (Byte) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun ByteArray.filter(predicate: (Byte) -> Boolean) : List<Byte> {
return filterTo(ArrayList<Byte>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun ByteArray.filterNot(predicate: (Byte) -> Boolean) : List<Byte> {
return filterNotTo(ArrayList<Byte>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Byte>> ByteArray.filterNotTo(result: C, predicate: (Byte) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Byte>> ByteArray.filterTo(result: C, predicate: (Byte) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun ByteArray.find(predicate: (Byte) -> Boolean) : Byte? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> ByteArray.flatMap(transform: (Byte)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> ByteArray.flatMapTo(result: C, transform: (Byte) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> ByteArray.fold(initial: R, operation: (R, Byte) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> ByteArray.foldRight(initial: R, operation: (Byte, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun ByteArray.forEach(operation: (Byte) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> ByteArray.groupBy(toKey: (Byte) -> K) : Map<K, List<Byte>> {
return groupByTo(HashMap<K, MutableList<Byte>>(), toKey)
}
public inline fun <K> ByteArray.groupByTo(result: MutableMap<K, MutableList<Byte>>, toKey: (Byte) -> K) : Map<K, MutableList<Byte>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Byte>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun ByteArray.indexOf(item: Byte) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun ByteArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun ByteArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ByteArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> ByteArray.map(transform : (Byte) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> ByteArray.mapTo(result: C, transform : (Byte) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun ByteArray.max() : Byte? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> ByteArray.maxBy(f: (Byte) -> R) : Byte? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun ByteArray.min() : Byte? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> ByteArray.minBy(f: (Byte) -> R) : Byte? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun ByteArray.partition(predicate: (Byte) -> Boolean) : Pair<List<Byte>, List<Byte>> {
val first = ArrayList<Byte>()
val second = ArrayList<Byte>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun ByteArray.plus(collection: Iterable<Byte>) : List<Byte> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun ByteArray.plus(element: Byte) : List<Byte> {
val answer = ArrayList<Byte>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun ByteArray.plus(iterator: Iterator<Byte>) : List<Byte> {
val answer = ArrayList<Byte>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun ByteArray.reduce(operation: (Byte, Byte) -> Byte) : Byte {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Byte = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun ByteArray.reduceRight(operation: (Byte, Byte) -> Byte) : Byte {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun ByteArray.reverse() : List<Byte> {
val list = toCollection(ArrayList<Byte>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> ByteArray.sortBy(f: (Byte) -> R) : List<Byte> {
val sortedList = toCollection(ArrayList<Byte>())
val sortBy: Comparator<Byte> = comparator<Byte> {(x: Byte, y: Byte) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun ByteArray.take(n: Int) : List<Byte> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun ByteArray.takeWhile(predicate: (Byte) -> Boolean) : List<Byte> {
return takeWhileTo(ArrayList<Byte>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Byte>> ByteArray.takeWhileTo(result: C, predicate: (Byte) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Byte>> ByteArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun ByteArray.toLinkedList() : LinkedList<Byte> {
return toCollection(LinkedList<Byte>())
}
/**
* Copies all elements into a [[List]]
*/
public fun ByteArray.toList() : List<Byte> {
return toCollection(ArrayList<Byte>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun ByteArray.toSet() : Set<Byte> {
return toCollection(LinkedHashSet<Byte>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun ByteArray.toSortedSet() : SortedSet<Byte> {
return toCollection(TreeSet<Byte>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun ByteArray.withIndices() : Iterator<Pair<Int, Byte>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun ByteArray.sum() : Int {
return fold(0, {a,b -> a+b})
}
@@ -1,475 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun CharArray.all(predicate: (Char) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun CharArray.any(predicate: (Char) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun CharArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun CharArray.count(predicate: (Char) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun CharArray.drop(n: Int) : List<Char> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun CharArray.dropWhile(predicate: (Char) -> Boolean) : List<Char> {
return dropWhileTo(ArrayList<Char>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Char>> CharArray.dropWhileTo(result: L, predicate: (Char) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun CharArray.filter(predicate: (Char) -> Boolean) : List<Char> {
return filterTo(ArrayList<Char>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun CharArray.filterNot(predicate: (Char) -> Boolean) : List<Char> {
return filterNotTo(ArrayList<Char>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Char>> CharArray.filterNotTo(result: C, predicate: (Char) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Char>> CharArray.filterTo(result: C, predicate: (Char) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun CharArray.find(predicate: (Char) -> Boolean) : Char? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> CharArray.flatMap(transform: (Char)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> CharArray.flatMapTo(result: C, transform: (Char) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> CharArray.fold(initial: R, operation: (R, Char) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> CharArray.foldRight(initial: R, operation: (Char, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun CharArray.forEach(operation: (Char) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> CharArray.groupBy(toKey: (Char) -> K) : Map<K, List<Char>> {
return groupByTo(HashMap<K, MutableList<Char>>(), toKey)
}
public inline fun <K> CharArray.groupByTo(result: MutableMap<K, MutableList<Char>>, toKey: (Char) -> K) : Map<K, MutableList<Char>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Char>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun CharArray.indexOf(item: Char) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun CharArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun CharArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun CharArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> CharArray.map(transform : (Char) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> CharArray.mapTo(result: C, transform : (Char) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun CharArray.max() : Char? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> CharArray.maxBy(f: (Char) -> R) : Char? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun CharArray.min() : Char? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> CharArray.minBy(f: (Char) -> R) : Char? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun CharArray.partition(predicate: (Char) -> Boolean) : Pair<List<Char>, List<Char>> {
val first = ArrayList<Char>()
val second = ArrayList<Char>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun CharArray.plus(collection: Iterable<Char>) : List<Char> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun CharArray.plus(element: Char) : List<Char> {
val answer = ArrayList<Char>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun CharArray.plus(iterator: Iterator<Char>) : List<Char> {
val answer = ArrayList<Char>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun CharArray.reduce(operation: (Char, Char) -> Char) : Char {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Char = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun CharArray.reduceRight(operation: (Char, Char) -> Char) : Char {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun CharArray.reverse() : List<Char> {
val list = toCollection(ArrayList<Char>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> CharArray.sortBy(f: (Char) -> R) : List<Char> {
val sortedList = toCollection(ArrayList<Char>())
val sortBy: Comparator<Char> = comparator<Char> {(x: Char, y: Char) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun CharArray.take(n: Int) : List<Char> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun CharArray.takeWhile(predicate: (Char) -> Boolean) : List<Char> {
return takeWhileTo(ArrayList<Char>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Char>> CharArray.takeWhileTo(result: C, predicate: (Char) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Char>> CharArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun CharArray.toLinkedList() : LinkedList<Char> {
return toCollection(LinkedList<Char>())
}
/**
* Copies all elements into a [[List]]
*/
public fun CharArray.toList() : List<Char> {
return toCollection(ArrayList<Char>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun CharArray.toSet() : Set<Char> {
return toCollection(LinkedHashSet<Char>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun CharArray.toSortedSet() : SortedSet<Char> {
return toCollection(TreeSet<Char>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun CharArray.withIndices() : Iterator<Pair<Int, Char>> {
return IndexIterator(iterator())
}
@@ -1,21 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> Collection<T?>.requireNoNulls() : Collection<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this")
}
}
return this as Collection<T>
}
@@ -1,482 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun DoubleArray.all(predicate: (Double) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun DoubleArray.any(predicate: (Double) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun DoubleArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun DoubleArray.count(predicate: (Double) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun DoubleArray.drop(n: Int) : List<Double> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun DoubleArray.dropWhile(predicate: (Double) -> Boolean) : List<Double> {
return dropWhileTo(ArrayList<Double>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Double>> DoubleArray.dropWhileTo(result: L, predicate: (Double) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun DoubleArray.filter(predicate: (Double) -> Boolean) : List<Double> {
return filterTo(ArrayList<Double>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun DoubleArray.filterNot(predicate: (Double) -> Boolean) : List<Double> {
return filterNotTo(ArrayList<Double>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Double>> DoubleArray.filterNotTo(result: C, predicate: (Double) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Double>> DoubleArray.filterTo(result: C, predicate: (Double) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun DoubleArray.find(predicate: (Double) -> Boolean) : Double? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> DoubleArray.flatMap(transform: (Double)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> DoubleArray.flatMapTo(result: C, transform: (Double) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> DoubleArray.fold(initial: R, operation: (R, Double) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> DoubleArray.foldRight(initial: R, operation: (Double, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun DoubleArray.forEach(operation: (Double) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> DoubleArray.groupBy(toKey: (Double) -> K) : Map<K, List<Double>> {
return groupByTo(HashMap<K, MutableList<Double>>(), toKey)
}
public inline fun <K> DoubleArray.groupByTo(result: MutableMap<K, MutableList<Double>>, toKey: (Double) -> K) : Map<K, MutableList<Double>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Double>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun DoubleArray.indexOf(item: Double) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun DoubleArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun DoubleArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun DoubleArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> DoubleArray.map(transform : (Double) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> DoubleArray.mapTo(result: C, transform : (Double) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun DoubleArray.max() : Double? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> DoubleArray.maxBy(f: (Double) -> R) : Double? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun DoubleArray.min() : Double? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> DoubleArray.minBy(f: (Double) -> R) : Double? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun DoubleArray.partition(predicate: (Double) -> Boolean) : Pair<List<Double>, List<Double>> {
val first = ArrayList<Double>()
val second = ArrayList<Double>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun DoubleArray.plus(collection: Iterable<Double>) : List<Double> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun DoubleArray.plus(element: Double) : List<Double> {
val answer = ArrayList<Double>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun DoubleArray.plus(iterator: Iterator<Double>) : List<Double> {
val answer = ArrayList<Double>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun DoubleArray.reduce(operation: (Double, Double) -> Double) : Double {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Double = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun DoubleArray.reduceRight(operation: (Double, Double) -> Double) : Double {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun DoubleArray.reverse() : List<Double> {
val list = toCollection(ArrayList<Double>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> DoubleArray.sortBy(f: (Double) -> R) : List<Double> {
val sortedList = toCollection(ArrayList<Double>())
val sortBy: Comparator<Double> = comparator<Double> {(x: Double, y: Double) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun DoubleArray.take(n: Int) : List<Double> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun DoubleArray.takeWhile(predicate: (Double) -> Boolean) : List<Double> {
return takeWhileTo(ArrayList<Double>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Double>> DoubleArray.takeWhileTo(result: C, predicate: (Double) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Double>> DoubleArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun DoubleArray.toLinkedList() : LinkedList<Double> {
return toCollection(LinkedList<Double>())
}
/**
* Copies all elements into a [[List]]
*/
public fun DoubleArray.toList() : List<Double> {
return toCollection(ArrayList<Double>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun DoubleArray.toSet() : Set<Double> {
return toCollection(LinkedHashSet<Double>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun DoubleArray.toSortedSet() : SortedSet<Double> {
return toCollection(TreeSet<Double>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun DoubleArray.withIndices() : Iterator<Pair<Int, Double>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun DoubleArray.sum() : Double {
return fold(0.0, {a,b -> a+b})
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,482 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun FloatArray.all(predicate: (Float) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun FloatArray.any(predicate: (Float) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun FloatArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun FloatArray.count(predicate: (Float) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun FloatArray.drop(n: Int) : List<Float> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun FloatArray.dropWhile(predicate: (Float) -> Boolean) : List<Float> {
return dropWhileTo(ArrayList<Float>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Float>> FloatArray.dropWhileTo(result: L, predicate: (Float) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun FloatArray.filter(predicate: (Float) -> Boolean) : List<Float> {
return filterTo(ArrayList<Float>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun FloatArray.filterNot(predicate: (Float) -> Boolean) : List<Float> {
return filterNotTo(ArrayList<Float>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Float>> FloatArray.filterNotTo(result: C, predicate: (Float) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Float>> FloatArray.filterTo(result: C, predicate: (Float) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun FloatArray.find(predicate: (Float) -> Boolean) : Float? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> FloatArray.flatMap(transform: (Float)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> FloatArray.flatMapTo(result: C, transform: (Float) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> FloatArray.fold(initial: R, operation: (R, Float) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> FloatArray.foldRight(initial: R, operation: (Float, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun FloatArray.forEach(operation: (Float) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> FloatArray.groupBy(toKey: (Float) -> K) : Map<K, List<Float>> {
return groupByTo(HashMap<K, MutableList<Float>>(), toKey)
}
public inline fun <K> FloatArray.groupByTo(result: MutableMap<K, MutableList<Float>>, toKey: (Float) -> K) : Map<K, MutableList<Float>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Float>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun FloatArray.indexOf(item: Float) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun FloatArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun FloatArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun FloatArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> FloatArray.map(transform : (Float) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> FloatArray.mapTo(result: C, transform : (Float) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun FloatArray.max() : Float? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> FloatArray.maxBy(f: (Float) -> R) : Float? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun FloatArray.min() : Float? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> FloatArray.minBy(f: (Float) -> R) : Float? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun FloatArray.partition(predicate: (Float) -> Boolean) : Pair<List<Float>, List<Float>> {
val first = ArrayList<Float>()
val second = ArrayList<Float>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun FloatArray.plus(collection: Iterable<Float>) : List<Float> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun FloatArray.plus(element: Float) : List<Float> {
val answer = ArrayList<Float>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun FloatArray.plus(iterator: Iterator<Float>) : List<Float> {
val answer = ArrayList<Float>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun FloatArray.reduce(operation: (Float, Float) -> Float) : Float {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Float = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun FloatArray.reduceRight(operation: (Float, Float) -> Float) : Float {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun FloatArray.reverse() : List<Float> {
val list = toCollection(ArrayList<Float>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> FloatArray.sortBy(f: (Float) -> R) : List<Float> {
val sortedList = toCollection(ArrayList<Float>())
val sortBy: Comparator<Float> = comparator<Float> {(x: Float, y: Float) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun FloatArray.take(n: Int) : List<Float> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun FloatArray.takeWhile(predicate: (Float) -> Boolean) : List<Float> {
return takeWhileTo(ArrayList<Float>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Float>> FloatArray.takeWhileTo(result: C, predicate: (Float) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Float>> FloatArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun FloatArray.toLinkedList() : LinkedList<Float> {
return toCollection(LinkedList<Float>())
}
/**
* Copies all elements into a [[List]]
*/
public fun FloatArray.toList() : List<Float> {
return toCollection(ArrayList<Float>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun FloatArray.toSet() : Set<Float> {
return toCollection(LinkedHashSet<Float>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun FloatArray.toSortedSet() : SortedSet<Float> {
return toCollection(TreeSet<Float>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun FloatArray.withIndices() : Iterator<Pair<Int, Float>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun FloatArray.sum() : Float {
return fold(0.toFloat(), {a,b -> a+b})
}
@@ -0,0 +1,836 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun <T> Array<out T>.partition(predicate: (T) -> Boolean) : Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun BooleanArray.partition(predicate: (Boolean) -> Boolean) : Pair<List<Boolean>, List<Boolean>> {
val first = ArrayList<Boolean>()
val second = ArrayList<Boolean>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun ByteArray.partition(predicate: (Byte) -> Boolean) : Pair<List<Byte>, List<Byte>> {
val first = ArrayList<Byte>()
val second = ArrayList<Byte>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun CharArray.partition(predicate: (Char) -> Boolean) : Pair<List<Char>, List<Char>> {
val first = ArrayList<Char>()
val second = ArrayList<Char>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun DoubleArray.partition(predicate: (Double) -> Boolean) : Pair<List<Double>, List<Double>> {
val first = ArrayList<Double>()
val second = ArrayList<Double>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun FloatArray.partition(predicate: (Float) -> Boolean) : Pair<List<Float>, List<Float>> {
val first = ArrayList<Float>()
val second = ArrayList<Float>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun IntArray.partition(predicate: (Int) -> Boolean) : Pair<List<Int>, List<Int>> {
val first = ArrayList<Int>()
val second = ArrayList<Int>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun LongArray.partition(predicate: (Long) -> Boolean) : Pair<List<Long>, List<Long>> {
val first = ArrayList<Long>()
val second = ArrayList<Long>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun ShortArray.partition(predicate: (Short) -> Boolean) : Pair<List<Short>, List<Short>> {
val first = ArrayList<Short>()
val second = ArrayList<Short>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean) : Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun <T> Stream<T>.partition(predicate: (T) -> Boolean) : Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun <T> Array<out T>.plus(array: Array<T>) : List<T> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun BooleanArray.plus(array: Array<Boolean>) : List<Boolean> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun ByteArray.plus(array: Array<Byte>) : List<Byte> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun CharArray.plus(array: Array<Char>) : List<Char> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun DoubleArray.plus(array: Array<Double>) : List<Double> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun FloatArray.plus(array: Array<Float>) : List<Float> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun IntArray.plus(array: Array<Int>) : List<Int> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun LongArray.plus(array: Array<Long>) : List<Long> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun ShortArray.plus(array: Array<Short>) : List<Short> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun <T> Iterable<T>.plus(array: Array<T>) : List<T> {
val answer = toArrayList()
answer.addAll(array)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun <T> Array<out T>.plus(collection: Iterable<T>) : List<T> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun BooleanArray.plus(collection: Iterable<Boolean>) : List<Boolean> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun ByteArray.plus(collection: Iterable<Byte>) : List<Byte> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun CharArray.plus(collection: Iterable<Char>) : List<Char> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun DoubleArray.plus(collection: Iterable<Double>) : List<Double> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun FloatArray.plus(collection: Iterable<Float>) : List<Float> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun IntArray.plus(collection: Iterable<Int>) : List<Int> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun LongArray.plus(collection: Iterable<Long>) : List<Long> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun ShortArray.plus(collection: Iterable<Short>) : List<Short> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a list containing all elements of original collection and then all elements of the given *collection*
*/
public fun <T> Iterable<T>.plus(collection: Iterable<T>) : List<T> {
val answer = toArrayList()
answer.addAll(collection)
return answer
}
/**
* Returns a stream containing all elements of original stream and then all elements of the given *collection*
*/
public fun <T> Stream<T>.plus(collection: Iterable<T>) : Stream<T> {
val answer = toArrayList()
answer.addAll(collection)
return answer.stream()
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun <T> Array<out T>.plus(element: T) : List<T> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun BooleanArray.plus(element: Boolean) : List<Boolean> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun ByteArray.plus(element: Byte) : List<Byte> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun CharArray.plus(element: Char) : List<Char> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun DoubleArray.plus(element: Double) : List<Double> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun FloatArray.plus(element: Float) : List<Float> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun IntArray.plus(element: Int) : List<Int> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun LongArray.plus(element: Long) : List<Long> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun ShortArray.plus(element: Short) : List<Short> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a list containing all elements of original collection and then the given element
*/
public fun <T> Iterable<T>.plus(element: T) : List<T> {
val answer = toArrayList()
answer.add(element)
return answer
}
/**
* Returns a stream containing all elements of original stream and then the given element
*/
public fun <T> Stream<T>.plus(element: T) : Stream<T> {
val answer = toArrayList()
answer.add(element)
return answer.stream()
}
/**
* Returns a stream containing all elements of original stream and then all elements of the given *stream*
*/
public fun <T> Stream<T>.plus(stream: Stream<T>) : Stream<T> {
val answer = toArrayList()
answer.addAll(stream)
return answer.stream()
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Array<out T>.zip(array: Array<R>) : List<Pair<T,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<T,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> BooleanArray.zip(array: Array<R>) : List<Pair<Boolean,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Boolean,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ByteArray.zip(array: Array<R>) : List<Pair<Byte,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Byte,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> CharArray.zip(array: Array<R>) : List<Pair<Char,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Char,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> DoubleArray.zip(array: Array<R>) : List<Pair<Double,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Double,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> FloatArray.zip(array: Array<R>) : List<Pair<Float,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Float,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> IntArray.zip(array: Array<R>) : List<Pair<Int,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Int,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> LongArray.zip(array: Array<R>) : List<Pair<Long,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Long,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ShortArray.zip(array: Array<R>) : List<Pair<Short,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<Short,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Iterable<T>.zip(array: Array<R>) : List<Pair<T,R>> {
val first = iterator()
val second = array.iterator()
val list = ArrayList<Pair<T,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Array<out T>.zip(collection: Iterable<R>) : List<Pair<T,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<T,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> BooleanArray.zip(collection: Iterable<R>) : List<Pair<Boolean,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Boolean,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ByteArray.zip(collection: Iterable<R>) : List<Pair<Byte,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Byte,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> CharArray.zip(collection: Iterable<R>) : List<Pair<Char,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Char,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> DoubleArray.zip(collection: Iterable<R>) : List<Pair<Double,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Double,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> FloatArray.zip(collection: Iterable<R>) : List<Pair<Float,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Float,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> IntArray.zip(collection: Iterable<R>) : List<Pair<Int,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Int,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> LongArray.zip(collection: Iterable<R>) : List<Pair<Long,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Long,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ShortArray.zip(collection: Iterable<R>) : List<Pair<Short,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<Short,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Iterable<T>.zip(collection: Iterable<R>) : List<Pair<T,R>> {
val first = iterator()
val second = collection.iterator()
val list = ArrayList<Pair<T,R>>()
while (first.hasNext() && second.hasNext()) {
list.add(first.next() to second.next())
}
return list
}
/**
* Returns a stream of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Stream<T>.zip(stream: Stream<R>) : Stream<Pair<T,R>> {
return ZippingStream(this, stream)
}
+61
View File
@@ -0,0 +1,61 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> Array<T?>.requireNoNulls() : Array<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this")
}
}
return this as Array<T>
}
/**
* Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> Iterable<T?>.requireNoNulls() : Iterable<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this")
}
}
return this as Iterable<T>
}
/**
* Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> List<T?>.requireNoNulls() : List<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this")
}
}
return this as List<T>
}
/**
* Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> Stream<T?>.requireNoNulls() : Stream<T> {
return FilteringStream(this) {
if (it == null) {
throw IllegalArgumentException("null element found in $this")
}
true
} as Stream<T>
}
@@ -1,482 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun IntArray.all(predicate: (Int) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun IntArray.any(predicate: (Int) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun IntArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun IntArray.count(predicate: (Int) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun IntArray.drop(n: Int) : List<Int> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun IntArray.dropWhile(predicate: (Int) -> Boolean) : List<Int> {
return dropWhileTo(ArrayList<Int>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Int>> IntArray.dropWhileTo(result: L, predicate: (Int) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun IntArray.filter(predicate: (Int) -> Boolean) : List<Int> {
return filterTo(ArrayList<Int>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun IntArray.filterNot(predicate: (Int) -> Boolean) : List<Int> {
return filterNotTo(ArrayList<Int>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Int>> IntArray.filterNotTo(result: C, predicate: (Int) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Int>> IntArray.filterTo(result: C, predicate: (Int) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun IntArray.find(predicate: (Int) -> Boolean) : Int? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> IntArray.flatMap(transform: (Int)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> IntArray.flatMapTo(result: C, transform: (Int) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> IntArray.fold(initial: R, operation: (R, Int) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> IntArray.foldRight(initial: R, operation: (Int, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun IntArray.forEach(operation: (Int) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> IntArray.groupBy(toKey: (Int) -> K) : Map<K, List<Int>> {
return groupByTo(HashMap<K, MutableList<Int>>(), toKey)
}
public inline fun <K> IntArray.groupByTo(result: MutableMap<K, MutableList<Int>>, toKey: (Int) -> K) : Map<K, MutableList<Int>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Int>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun IntArray.indexOf(item: Int) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun IntArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun IntArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun IntArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> IntArray.map(transform : (Int) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> IntArray.mapTo(result: C, transform : (Int) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun IntArray.max() : Int? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> IntArray.maxBy(f: (Int) -> R) : Int? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun IntArray.min() : Int? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> IntArray.minBy(f: (Int) -> R) : Int? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun IntArray.partition(predicate: (Int) -> Boolean) : Pair<List<Int>, List<Int>> {
val first = ArrayList<Int>()
val second = ArrayList<Int>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun IntArray.plus(collection: Iterable<Int>) : List<Int> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun IntArray.plus(element: Int) : List<Int> {
val answer = ArrayList<Int>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun IntArray.plus(iterator: Iterator<Int>) : List<Int> {
val answer = ArrayList<Int>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun IntArray.reduce(operation: (Int, Int) -> Int) : Int {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Int = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun IntArray.reduceRight(operation: (Int, Int) -> Int) : Int {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun IntArray.reverse() : List<Int> {
val list = toCollection(ArrayList<Int>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> IntArray.sortBy(f: (Int) -> R) : List<Int> {
val sortedList = toCollection(ArrayList<Int>())
val sortBy: Comparator<Int> = comparator<Int> {(x: Int, y: Int) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun IntArray.take(n: Int) : List<Int> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun IntArray.takeWhile(predicate: (Int) -> Boolean) : List<Int> {
return takeWhileTo(ArrayList<Int>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Int>> IntArray.takeWhileTo(result: C, predicate: (Int) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Int>> IntArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun IntArray.toLinkedList() : LinkedList<Int> {
return toCollection(LinkedList<Int>())
}
/**
* Copies all elements into a [[List]]
*/
public fun IntArray.toList() : List<Int> {
return toCollection(ArrayList<Int>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun IntArray.toSet() : Set<Int> {
return toCollection(LinkedHashSet<Int>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun IntArray.toSortedSet() : SortedSet<Int> {
return toCollection(TreeSet<Int>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun IntArray.withIndices() : Iterator<Pair<Int, Int>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun IntArray.sum() : Int {
return fold(0, {a,b -> a+b})
}
@@ -1,476 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Iterable<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun <T> Iterable<T>.count(predicate: (T) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun <T> Iterable<T>.drop(n: Int) : List<T> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean) : List<T> {
return dropWhileTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <T, L: MutableList<in T>> Iterable<T>.dropWhileTo(result: L, predicate: (T) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean) : List<T> {
return filterTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean) : List<T> {
return filterNotTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing all the non-*null* elements
*/
public fun <T:Any> Iterable<T?>.filterNotNull() : List<T> {
return filterNotNullTo<T, ArrayList<T>>(ArrayList<T>())
}
/**
* Filters all non-*null* elements into the given list
*/
public fun <T:Any, C: MutableCollection<in T>> Iterable<T?>.filterNotNullTo(result: C) : C {
for (element in this) if (element != null) result.add(element)
return result
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <T, C: MutableCollection<in T>> Iterable<T>.filterNotTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <T, C: MutableCollection<in T>> Iterable<T>.filterTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun <T:Any> Iterable<T>.find(predicate: (T) -> Boolean) : T? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <T, R> Iterable<T>.flatMap(transform: (T)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <T, R, C: MutableCollection<in R>> Iterable<T>.flatMapTo(result: C, transform: (T) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (R, T) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Performs the given *operation* on each element
*/
public inline fun <T> Iterable<T>.forEach(operation: (T) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <T, K> Iterable<T>.groupBy(toKey: (T) -> K) : Map<K, List<T>> {
return groupByTo(HashMap<K, MutableList<T>>(), toKey)
}
public inline fun <T, K> Iterable<T>.groupByTo(result: MutableMap<K, MutableList<T>>, toKey: (T) -> K) : Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return result
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Iterable<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <T, R> Iterable<T>.map(transform : (T) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <T, R, C: MutableCollection<in R>> Iterable<T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun <T: Comparable<T>> Iterable<T>.max() : T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>, T: Any> Iterable<T>.maxBy(f: (T) -> R) : T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = f(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun <T: Comparable<T>> Iterable<T>.min() : T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>, T: Any> Iterable<T>.minBy(f: (T) -> R) : T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = f(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean) : Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun <T> Iterable<T>.plus(collection: Iterable<T>) : List<T> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun <T> Iterable<T>.plus(element: T) : List<T> {
val answer = ArrayList<T>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun <T> Iterable<T>.plus(iterator: Iterator<T>) : List<T> {
val answer = ArrayList<T>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun <T> Iterable<T>.reduce(operation: (T, T) -> T) : T {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: T = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> Iterable<T?>.requireNoNulls() : Iterable<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this")
}
}
return this as Iterable<T>
}
/**
* Reverses the order the elements into a list
*/
public fun <T> Iterable<T>.reverse() : List<T> {
val list = toCollection(ArrayList<T>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <T, R: Comparable<R>> Iterable<T>.sortBy(f: (T) -> R) : List<T> {
val sortedList = toCollection(ArrayList<T>())
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun <T> Iterable<T>.take(n: Int) : List<T> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean) : List<T> {
return takeWhileTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <T, C: MutableCollection<in T>> Iterable<T>.takeWhileTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <T, C: MutableCollection<in T>> Iterable<T>.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun <T> Iterable<T>.toLinkedList() : LinkedList<T> {
return toCollection(LinkedList<T>())
}
/**
* Copies all elements into a [[List]]
*/
public fun <T> Iterable<T>.toList() : List<T> {
return toCollection(ArrayList<T>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun <T> Iterable<T>.toSet() : Set<T> {
return toCollection(LinkedHashSet<T>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun <T> Iterable<T>.toSortedSet() : SortedSet<T> {
return toCollection(TreeSet<T>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun <T> Iterable<T>.withIndices() : Iterator<Pair<Int, T>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun Iterable<Int>.sum() : Int {
return fold(0, {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Iterable<Long>.sum() : Long {
return fold(0.toLong(), {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Iterable<Float>.sum() : Float {
return fold(0.toFloat(), {a,b -> a+b})
}
/**
* Sums up the elements
*/
public fun Iterable<Double>.sum() : Double {
return fold(0.0, {a,b -> a+b})
}
@@ -1,482 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun LongArray.all(predicate: (Long) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun LongArray.any(predicate: (Long) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun LongArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun LongArray.count(predicate: (Long) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun LongArray.drop(n: Int) : List<Long> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun LongArray.dropWhile(predicate: (Long) -> Boolean) : List<Long> {
return dropWhileTo(ArrayList<Long>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Long>> LongArray.dropWhileTo(result: L, predicate: (Long) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun LongArray.filter(predicate: (Long) -> Boolean) : List<Long> {
return filterTo(ArrayList<Long>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun LongArray.filterNot(predicate: (Long) -> Boolean) : List<Long> {
return filterNotTo(ArrayList<Long>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Long>> LongArray.filterNotTo(result: C, predicate: (Long) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Long>> LongArray.filterTo(result: C, predicate: (Long) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun LongArray.find(predicate: (Long) -> Boolean) : Long? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> LongArray.flatMap(transform: (Long)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> LongArray.flatMapTo(result: C, transform: (Long) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> LongArray.fold(initial: R, operation: (R, Long) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> LongArray.foldRight(initial: R, operation: (Long, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun LongArray.forEach(operation: (Long) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> LongArray.groupBy(toKey: (Long) -> K) : Map<K, List<Long>> {
return groupByTo(HashMap<K, MutableList<Long>>(), toKey)
}
public inline fun <K> LongArray.groupByTo(result: MutableMap<K, MutableList<Long>>, toKey: (Long) -> K) : Map<K, MutableList<Long>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Long>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun LongArray.indexOf(item: Long) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun LongArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun LongArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun LongArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> LongArray.map(transform : (Long) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> LongArray.mapTo(result: C, transform : (Long) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun LongArray.max() : Long? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> LongArray.maxBy(f: (Long) -> R) : Long? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun LongArray.min() : Long? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> LongArray.minBy(f: (Long) -> R) : Long? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun LongArray.partition(predicate: (Long) -> Boolean) : Pair<List<Long>, List<Long>> {
val first = ArrayList<Long>()
val second = ArrayList<Long>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun LongArray.plus(collection: Iterable<Long>) : List<Long> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun LongArray.plus(element: Long) : List<Long> {
val answer = ArrayList<Long>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun LongArray.plus(iterator: Iterator<Long>) : List<Long> {
val answer = ArrayList<Long>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun LongArray.reduce(operation: (Long, Long) -> Long) : Long {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Long = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun LongArray.reduceRight(operation: (Long, Long) -> Long) : Long {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun LongArray.reverse() : List<Long> {
val list = toCollection(ArrayList<Long>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> LongArray.sortBy(f: (Long) -> R) : List<Long> {
val sortedList = toCollection(ArrayList<Long>())
val sortBy: Comparator<Long> = comparator<Long> {(x: Long, y: Long) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun LongArray.take(n: Int) : List<Long> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun LongArray.takeWhile(predicate: (Long) -> Boolean) : List<Long> {
return takeWhileTo(ArrayList<Long>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Long>> LongArray.takeWhileTo(result: C, predicate: (Long) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Long>> LongArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun LongArray.toLinkedList() : LinkedList<Long> {
return toCollection(LinkedList<Long>())
}
/**
* Copies all elements into a [[List]]
*/
public fun LongArray.toList() : List<Long> {
return toCollection(ArrayList<Long>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun LongArray.toSet() : Set<Long> {
return toCollection(LinkedHashSet<Long>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun LongArray.toSortedSet() : SortedSet<Long> {
return toCollection(TreeSet<Long>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun LongArray.withIndices() : Iterator<Pair<Int, Long>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun LongArray.sum() : Long {
return fold(0.toLong(), {a,b -> a+b})
}
+858
View File
@@ -0,0 +1,858 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <T, R> Array<out T>.flatMap(transform: (T)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> BooleanArray.flatMap(transform: (Boolean)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> ByteArray.flatMap(transform: (Byte)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> CharArray.flatMap(transform: (Char)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> DoubleArray.flatMap(transform: (Double)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> FloatArray.flatMap(transform: (Float)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> IntArray.flatMap(transform: (Int)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> LongArray.flatMap(transform: (Long)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <R> ShortArray.flatMap(transform: (Short)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <T, R> Iterable<T>.flatMap(transform: (T)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection
*/
public inline fun <K, V, R> Map<K,V>.flatMap(transform: (Map.Entry<K,V>)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single stream of all elements streamed from results of *transform* function being invoked on each element of original stream
*/
public fun <T, R> Stream<T>.flatMap(transform: (T)-> Stream<R>) : Stream<R> {
return FlatteningStream(this, transform)
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <T, R, C: MutableCollection<in R>> Array<out T>.flatMapTo(collection: C, transform: (T) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> BooleanArray.flatMapTo(collection: C, transform: (Boolean) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> ByteArray.flatMapTo(collection: C, transform: (Byte) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> CharArray.flatMapTo(collection: C, transform: (Char) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> DoubleArray.flatMapTo(collection: C, transform: (Double) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> FloatArray.flatMapTo(collection: C, transform: (Float) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> IntArray.flatMapTo(collection: C, transform: (Int) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> LongArray.flatMapTo(collection: C, transform: (Long) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> ShortArray.flatMapTo(collection: C, transform: (Short) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <T, R, C: MutableCollection<in R>> Iterable<T>.flatMapTo(collection: C, transform: (T) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*
*/
public inline fun <K, V, R, C: MutableCollection<in R>> Map<K,V>.flatMapTo(collection: C, transform: (Map.Entry<K,V>) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original stream, to the given *collection*
*/
public inline fun <T, R, C: MutableCollection<in R>> Stream<T>.flatMapTo(collection: C, transform: (T) -> Stream<R>) : C {
for (element in this) {
val list = transform(element)
collection.addAll(list)
}
return collection
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <T, K> Array<out T>.groupBy(toKey: (T) -> K) : Map<K, List<T>> {
return groupByTo(HashMap<K, MutableList<T>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> BooleanArray.groupBy(toKey: (Boolean) -> K) : Map<K, List<Boolean>> {
return groupByTo(HashMap<K, MutableList<Boolean>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> ByteArray.groupBy(toKey: (Byte) -> K) : Map<K, List<Byte>> {
return groupByTo(HashMap<K, MutableList<Byte>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> CharArray.groupBy(toKey: (Char) -> K) : Map<K, List<Char>> {
return groupByTo(HashMap<K, MutableList<Char>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> DoubleArray.groupBy(toKey: (Double) -> K) : Map<K, List<Double>> {
return groupByTo(HashMap<K, MutableList<Double>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> FloatArray.groupBy(toKey: (Float) -> K) : Map<K, List<Float>> {
return groupByTo(HashMap<K, MutableList<Float>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> IntArray.groupBy(toKey: (Int) -> K) : Map<K, List<Int>> {
return groupByTo(HashMap<K, MutableList<Int>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> LongArray.groupBy(toKey: (Long) -> K) : Map<K, List<Long>> {
return groupByTo(HashMap<K, MutableList<Long>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <K> ShortArray.groupBy(toKey: (Short) -> K) : Map<K, List<Short>> {
return groupByTo(HashMap<K, MutableList<Short>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <T, K> Iterable<T>.groupBy(toKey: (T) -> K) : Map<K, List<T>> {
return groupByTo(HashMap<K, MutableList<T>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <V, K> Map<K,V>.groupBy(toKey: (Map.Entry<K,V>) -> K) : Map<K, List<Map.Entry<K,V>>> {
return groupByTo(HashMap<K, MutableList<Map.Entry<K,V>>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <T, K> Stream<T>.groupBy(toKey: (T) -> K) : Map<K, List<T>> {
return groupByTo(HashMap<K, MutableList<T>>(), toKey)
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <T, K> Array<out T>.groupByTo(map: MutableMap<K, MutableList<T>>, toKey: (T) -> K) : Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> BooleanArray.groupByTo(map: MutableMap<K, MutableList<Boolean>>, toKey: (Boolean) -> K) : Map<K, MutableList<Boolean>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Boolean>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> ByteArray.groupByTo(map: MutableMap<K, MutableList<Byte>>, toKey: (Byte) -> K) : Map<K, MutableList<Byte>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Byte>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> CharArray.groupByTo(map: MutableMap<K, MutableList<Char>>, toKey: (Char) -> K) : Map<K, MutableList<Char>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Char>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> DoubleArray.groupByTo(map: MutableMap<K, MutableList<Double>>, toKey: (Double) -> K) : Map<K, MutableList<Double>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Double>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> FloatArray.groupByTo(map: MutableMap<K, MutableList<Float>>, toKey: (Float) -> K) : Map<K, MutableList<Float>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Float>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> IntArray.groupByTo(map: MutableMap<K, MutableList<Int>>, toKey: (Int) -> K) : Map<K, MutableList<Int>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Int>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> LongArray.groupByTo(map: MutableMap<K, MutableList<Long>>, toKey: (Long) -> K) : Map<K, MutableList<Long>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Long>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <K> ShortArray.groupByTo(map: MutableMap<K, MutableList<Short>>, toKey: (Short) -> K) : Map<K, MutableList<Short>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Short>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <T, K> Iterable<T>.groupByTo(map: MutableMap<K, MutableList<T>>, toKey: (T) -> K) : Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <V, K> Map<K,V>.groupByTo(map: MutableMap<K, MutableList<Map.Entry<K,V>>>, toKey: (Map.Entry<K,V>) -> K) : Map<K, MutableList<Map.Entry<K,V>>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<Map.Entry<K,V>>() }
list.add(element)
}
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <T, K> Stream<T>.groupByTo(map: MutableMap<K, MutableList<T>>, toKey: (T) -> K) : Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return map
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <T, R> Array<out T>.map(transform : (T) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> BooleanArray.map(transform : (Boolean) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> ByteArray.map(transform : (Byte) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> CharArray.map(transform : (Char) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> DoubleArray.map(transform : (Double) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> FloatArray.map(transform : (Float) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> IntArray.map(transform : (Int) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> LongArray.map(transform : (Long) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <R> ShortArray.map(transform : (Short) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <T, R> Iterable<T>.map(transform : (T) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each element of the original collection
*/
public inline fun <K, V, R> Map<K,V>.map(transform : (Map.Entry<K,V>) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a stream containing the results of applying the given *transform* function to each element of the original stream
*/
public fun <T, R> Stream<T>.map(transform : (T) -> R) : Stream<R> {
return TransformingStream(this, transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each non-null element of the original collection
*/
public fun <T: Any, R> Array<T?>.mapNotNull(transform : (T) -> R) : List<R> {
return mapNotNullTo(ArrayList<R>(), transform)
}
/**
* Returns a list containing the results of applying the given *transform* function to each non-null element of the original collection
*/
public fun <T: Any, R> Iterable<T?>.mapNotNull(transform : (T) -> R) : List<R> {
return mapNotNullTo(ArrayList<R>(), transform)
}
/**
* Returns a stream containing the results of applying the given *transform* function to each non-null element of the original stream
*/
public fun <T: Any, R> Stream<T?>.mapNotNull(transform : (T) -> R) : Stream<R> {
return TransformingStream(FilteringStream(this, false, { it != null }) as Stream<T>, transform)
}
/**
* Appends transformed non-null elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <T: Any, R, C: MutableCollection<in R>> Array<T?>.mapNotNullTo(collection: C, transform : (T) -> R) : C {
for (element in this) {
if (element != null) {
collection.add(transform(element))
}
}
return collection
}
/**
* Appends transformed non-null elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <T: Any, R, C: MutableCollection<in R>> Iterable<T?>.mapNotNullTo(collection: C, transform : (T) -> R) : C {
for (element in this) {
if (element != null) {
collection.add(transform(element))
}
}
return collection
}
/**
* Appends transformed non-null elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <T: Any, R, C: MutableCollection<in R>> Stream<T?>.mapNotNullTo(collection: C, transform : (T) -> R) : C {
for (element in this) {
if (element != null) {
collection.add(transform(element))
}
}
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <T, R, C: MutableCollection<in R>> Array<out T>.mapTo(collection: C, transform : (T) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> BooleanArray.mapTo(collection: C, transform : (Boolean) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> ByteArray.mapTo(collection: C, transform : (Byte) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> CharArray.mapTo(collection: C, transform : (Char) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> DoubleArray.mapTo(collection: C, transform : (Double) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> FloatArray.mapTo(collection: C, transform : (Float) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> IntArray.mapTo(collection: C, transform : (Int) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> LongArray.mapTo(collection: C, transform : (Long) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <R, C: MutableCollection<in R>> ShortArray.mapTo(collection: C, transform : (Short) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <T, R, C: MutableCollection<in R>> Iterable<T>.mapTo(collection: C, transform : (T) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <K, V, R, C: MutableCollection<in R>> Map<K,V>.mapTo(collection: C, transform : (Map.Entry<K,V>) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Appends transformed elements of original collection using the given *transform* function
* to the given *collection*
*/
public inline fun <T, R, C: MutableCollection<in R>> Stream<T>.mapTo(collection: C, transform : (T) -> R) : C {
for (item in this)
collection.add(transform(item))
return collection
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun <T> Array<out T>.withIndices() : List<Pair<Int, T>> {
var index = 0
return mapTo(ArrayList<Pair<Int, T>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun BooleanArray.withIndices() : List<Pair<Int, Boolean>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Boolean>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun ByteArray.withIndices() : List<Pair<Int, Byte>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Byte>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun CharArray.withIndices() : List<Pair<Int, Char>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Char>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun DoubleArray.withIndices() : List<Pair<Int, Double>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Double>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun FloatArray.withIndices() : List<Pair<Int, Float>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Float>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun IntArray.withIndices() : List<Pair<Int, Int>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Int>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun LongArray.withIndices() : List<Pair<Int, Long>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Long>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun ShortArray.withIndices() : List<Pair<Int, Short>> {
var index = 0
return mapTo(ArrayList<Pair<Int, Short>>(), { index++ to it })
}
/**
* Returns a list containing pairs of each element of the original collection and their index
*/
public fun <T> Iterable<T>.withIndices() : List<Pair<Int, T>> {
var index = 0
return mapTo(ArrayList<Pair<Int, T>>(), { index++ to it })
}
/**
* Returns a stream containing pairs of each element of the original collection and their index
*/
public fun <T> Stream<T>.withIndices() : Stream<Pair<Int, T>> {
var index = 0
return TransformingStream(this, { index++ to it })
}
+217
View File
@@ -0,0 +1,217 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns the sum of all elements in the collection
*/
public fun Iterable<Int>.sum() : Int {
val iterator = iterator()
var sum : Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Iterable<Long>.sum() : Long {
val iterator = iterator()
var sum : Long = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Iterable<Double>.sum() : Double {
val iterator = iterator()
var sum : Double = 0.0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Iterable<Float>.sum() : Float {
val iterator = iterator()
var sum : Float = 0.0f
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Array<out Int>.sum() : Int {
val iterator = iterator()
var sum : Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun IntArray.sum() : Int {
val iterator = iterator()
var sum : Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Array<out Long>.sum() : Long {
val iterator = iterator()
var sum : Long = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun LongArray.sum() : Long {
val iterator = iterator()
var sum : Long = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Array<out Byte>.sum() : Int {
val iterator = iterator()
var sum : Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun ByteArray.sum() : Int {
val iterator = iterator()
var sum : Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Array<out Short>.sum() : Int {
val iterator = iterator()
var sum : Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun ShortArray.sum() : Int {
val iterator = iterator()
var sum : Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Array<out Double>.sum() : Double {
val iterator = iterator()
var sum : Double = 0.0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun DoubleArray.sum() : Double {
val iterator = iterator()
var sum : Double = 0.0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Array<out Float>.sum() : Float {
val iterator = iterator()
var sum : Float = 0.0f
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun FloatArray.sum() : Float {
val iterator = iterator()
var sum : Float = 0.0f
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
+194
View File
@@ -0,0 +1,194 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns a list with elements in reversed order
*/
public fun <T> Array<out T>.reverse() : List<T> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun BooleanArray.reverse() : List<Boolean> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun ByteArray.reverse() : List<Byte> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun CharArray.reverse() : List<Char> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun DoubleArray.reverse() : List<Double> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun FloatArray.reverse() : List<Float> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun IntArray.reverse() : List<Int> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun LongArray.reverse() : List<Long> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun ShortArray.reverse() : List<Short> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a list with elements in reversed order
*/
public fun <T> Iterable<T>.reverse() : List<T> {
val list = toArrayList()
Collections.reverse(list)
return list
}
/**
* Returns a sorted list of all elements
*/
public fun <T: Comparable<T>> Iterable<T>.sort() : List<T> {
val sortedList = toArrayList()
java.util.Collections.sort(sortedList)
return sortedList
}
/**
* Returns a list of all elements, sorted by the specified *comparator*
*/
public fun <T> Array<out T>.sortBy(comparator : Comparator<T>) : List<T> {
val sortedList = toArrayList()
java.util.Collections.sort(sortedList, comparator)
return sortedList
}
/**
* Returns a list of all elements, sorted by the specified *comparator*
*/
public fun <T> Iterable<T>.sortBy(comparator : Comparator<T>) : List<T> {
val sortedList = toArrayList()
java.util.Collections.sort(sortedList, comparator)
return sortedList
}
/**
* Returns a list of all elements, sorted by results of specified *order* function.
*/
public inline fun <T, R: Comparable<R>> Array<out T>.sortBy(order: (T) -> R) : List<T> {
val sortedList = toArrayList()
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) -> order(x).compareTo(order(y))}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list of all elements, sorted by results of specified *order* function.
*/
public inline fun <T, R: Comparable<R>> Iterable<T>.sortBy(order: (T) -> R) : List<T> {
val sortedList = toArrayList()
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) -> order(x).compareTo(order(y))}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a sorted list of all elements
*/
public fun <T: Comparable<T>> Iterable<T>.sortDescending() : List<T> {
val sortedList = toArrayList()
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) -> -x.compareTo(y)}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list of all elements, sorted by results of specified *order* function.
*/
public inline fun <T, R: Comparable<R>> Array<out T>.sortDescendingBy(order: (T) -> R) : List<T> {
val sortedList = toArrayList()
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) -> -order(x).compareTo(order(y))}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list of all elements, sorted by results of specified *order* function.
*/
public inline fun <T, R: Comparable<R>> Iterable<T>.sortDescendingBy(order: (T) -> R) : List<T> {
val sortedList = toArrayList()
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) -> -order(x).compareTo(order(y))}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
@@ -1,482 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun ShortArray.all(predicate: (Short) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns *true* if any elements match the given *predicate*
*/
public inline fun ShortArray.any(predicate: (Short) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ShortArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Returns the number of elements which match the given *predicate*
*/
public inline fun ShortArray.count(predicate: (Short) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Returns a list containing everything but the first *n* elements
*/
public fun ShortArray.drop(n: Int) : List<Short> {
return dropWhile(countTo(n))
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun ShortArray.dropWhile(predicate: (Short) -> Boolean) : List<Short> {
return dropWhileTo(ArrayList<Short>(), predicate)
}
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
public inline fun <L: MutableList<in Short>> ShortArray.dropWhileTo(result: L, predicate: (Short) -> Boolean) : L {
var start = true
for (element in this) {
if (start && predicate(element)) {
// ignore
} else {
start = false
result.add(element)
}
}
return result
}
/**
* Returns a list containing all elements which match the given *predicate*
*/
public inline fun ShortArray.filter(predicate: (Short) -> Boolean) : List<Short> {
return filterTo(ArrayList<Short>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun ShortArray.filterNot(predicate: (Short) -> Boolean) : List<Short> {
return filterNotTo(ArrayList<Short>(), predicate)
}
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
public inline fun <C: MutableCollection<in Short>> ShortArray.filterNotTo(result: C, predicate: (Short) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
}
/**
* Filters all elements which match the given predicate into the given list
*/
public inline fun <C: MutableCollection<in Short>> ShortArray.filterTo(result: C, predicate: (Short) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
}
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
public inline fun ShortArray.find(predicate: (Short) -> Boolean) : Short? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single list
*/
public inline fun <R> ShortArray.flatMap(transform: (Short)-> Iterable<R>) : List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
public inline fun <R, C: MutableCollection<in R>> ShortArray.flatMapTo(result: C, transform: (Short) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
for (r in list) result.add(r)
}
return result
}
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> ShortArray.fold(initial: R, operation: (R, Short) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
return answer
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <R> ShortArray.foldRight(initial: R, operation: (Short, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Performs the given *operation* on each element
*/
public inline fun ShortArray.forEach(operation: (Short) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
public inline fun <K> ShortArray.groupBy(toKey: (Short) -> K) : Map<K, List<Short>> {
return groupByTo(HashMap<K, MutableList<Short>>(), toKey)
}
public inline fun <K> ShortArray.groupByTo(result: MutableMap<K, MutableList<Short>>, toKey: (Short) -> K) : Map<K, MutableList<Short>> {
for (element in this) {
val key = toKey(element)
val list = result.getOrPut(key) { ArrayList<Short>() }
list.add(element)
}
return result
}
/**
* Returns first index of item, or -1 if the array does not contain item
*/
public fun ShortArray.indexOf(item: Short) : Int {
for (i in indices) {
if (item == this[i]) {
return i
}
}
return -1
}
/**
* Returns true if the array is empty
*/
public fun ShortArray.isEmpty() : Boolean {
return size == 0
}
/**
* Returns true if the array is empty
*/
public fun ShortArray.isNotEmpty() : Boolean {
return !isEmpty()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ShortArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Returns a new List containing the results of applying the given *transform* function to each element in this collection
*/
public inline fun <R> ShortArray.map(transform : (Short) -> R) : List<R> {
return mapTo(ArrayList<R>(), transform)
}
/**
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <R, C: MutableCollection<in R>> ShortArray.mapTo(result: C, transform : (Short) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun ShortArray.max() : Short? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> ShortArray.maxBy(f: (Short) -> R) : Short? {
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun ShortArray.min() : Short? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R: Comparable<R>> ShortArray.minBy(f: (Short) -> R) : Short? {
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Partitions this collection into a pair of collections
*/
public inline fun ShortArray.partition(predicate: (Short) -> Boolean) : Pair<List<Short>, List<Short>> {
val first = ArrayList<Short>()
val second = ArrayList<Short>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
public fun ShortArray.plus(collection: Iterable<Short>) : List<Short> {
return plus(collection.iterator())
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
public fun ShortArray.plus(element: Short) : List<Short> {
val answer = ArrayList<Short>()
toCollection(answer)
answer.add(element)
return answer
}
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
public fun ShortArray.plus(iterator: Iterator<Short>) : List<Short> {
val answer = ArrayList<Short>()
toCollection(answer)
for (element in iterator) {
answer.add(element)
}
return answer
}
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
public inline fun ShortArray.reduce(operation: (Short, Short) -> Short) : Short {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Short = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun ShortArray.reduceRight(operation: (Short, Short) -> Short) : Short {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Reverses the order the elements into a list
*/
public fun ShortArray.reverse() : List<Short> {
val list = toCollection(ArrayList<Short>())
Collections.reverse(list)
return list
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
public inline fun <R: Comparable<R>> ShortArray.sortBy(f: (Short) -> R) : List<Short> {
val sortedList = toCollection(ArrayList<Short>())
val sortBy: Comparator<Short> = comparator<Short> {(x: Short, y: Short) ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
}
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
/**
* Returns a list containing the first *n* elements
*/
public fun ShortArray.take(n: Int) : List<Short> {
return takeWhile(countTo(n))
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun ShortArray.takeWhile(predicate: (Short) -> Boolean) : List<Short> {
return takeWhileTo(ArrayList<Short>(), predicate)
}
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
public inline fun <C: MutableCollection<in Short>> ShortArray.takeWhileTo(result: C, predicate: (Short) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
/**
* Copies all elements into the given collection
*/
public fun <C: MutableCollection<in Short>> ShortArray.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
}
/**
* Copies all elements into a [[LinkedList]]
*/
public fun ShortArray.toLinkedList() : LinkedList<Short> {
return toCollection(LinkedList<Short>())
}
/**
* Copies all elements into a [[List]]
*/
public fun ShortArray.toList() : List<Short> {
return toCollection(ArrayList<Short>())
}
/**
* Copies all elements into a [[Set]]
*/
public fun ShortArray.toSet() : Set<Short> {
return toCollection(LinkedHashSet<Short>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
public fun ShortArray.toSortedSet() : SortedSet<Short> {
return toCollection(TreeSet<Short>())
}
/**
* Returns an iterator of Pairs(index, data)
*/
public fun ShortArray.withIndices() : Iterator<Pair<Int, Short>> {
return IndexIterator(iterator())
}
/**
* Sums up the elements
*/
public fun ShortArray.sum() : Int {
return fold(0, {a,b -> a+b})
}
@@ -0,0 +1,720 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Returns an ArrayList of all elements
*/
public fun <T> Array<out T>.toArrayList() : ArrayList<T> {
val list = ArrayList<T>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun BooleanArray.toArrayList() : ArrayList<Boolean> {
val list = ArrayList<Boolean>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun ByteArray.toArrayList() : ArrayList<Byte> {
val list = ArrayList<Byte>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun CharArray.toArrayList() : ArrayList<Char> {
val list = ArrayList<Char>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun DoubleArray.toArrayList() : ArrayList<Double> {
val list = ArrayList<Double>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun FloatArray.toArrayList() : ArrayList<Float> {
val list = ArrayList<Float>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun IntArray.toArrayList() : ArrayList<Int> {
val list = ArrayList<Int>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun LongArray.toArrayList() : ArrayList<Long> {
val list = ArrayList<Long>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun ShortArray.toArrayList() : ArrayList<Short> {
val list = ArrayList<Short>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns an ArrayList of all elements
*/
public fun <T> Iterable<T>.toArrayList() : ArrayList<T> {
return toCollection(ArrayList<T>())
}
/**
* Returns an ArrayList of all elements
*/
public fun <T> Stream<T>.toArrayList() : ArrayList<T> {
return toCollection(ArrayList<T>())
}
/**
* Appends all elements to the given *collection*
*/
public fun <T, C : MutableCollection<in T>> Array<out T>.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Boolean>> BooleanArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Byte>> ByteArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Char>> CharArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Double>> DoubleArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Float>> FloatArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Int>> IntArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Long>> LongArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <C : MutableCollection<in Short>> ShortArray.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <T, C : MutableCollection<in T>> Stream<T>.toCollection(collection : C) : C {
for (item in this) {
collection.add(item)
}
return collection
}
/**
* Returns a HashSet of all elements
*/
public fun <T> Array<out T>.toHashSet() : HashSet<T> {
return toCollection(HashSet<T>())
}
/**
* Returns a HashSet of all elements
*/
public fun BooleanArray.toHashSet() : HashSet<Boolean> {
return toCollection(HashSet<Boolean>())
}
/**
* Returns a HashSet of all elements
*/
public fun ByteArray.toHashSet() : HashSet<Byte> {
return toCollection(HashSet<Byte>())
}
/**
* Returns a HashSet of all elements
*/
public fun CharArray.toHashSet() : HashSet<Char> {
return toCollection(HashSet<Char>())
}
/**
* Returns a HashSet of all elements
*/
public fun DoubleArray.toHashSet() : HashSet<Double> {
return toCollection(HashSet<Double>())
}
/**
* Returns a HashSet of all elements
*/
public fun FloatArray.toHashSet() : HashSet<Float> {
return toCollection(HashSet<Float>())
}
/**
* Returns a HashSet of all elements
*/
public fun IntArray.toHashSet() : HashSet<Int> {
return toCollection(HashSet<Int>())
}
/**
* Returns a HashSet of all elements
*/
public fun LongArray.toHashSet() : HashSet<Long> {
return toCollection(HashSet<Long>())
}
/**
* Returns a HashSet of all elements
*/
public fun ShortArray.toHashSet() : HashSet<Short> {
return toCollection(HashSet<Short>())
}
/**
* Returns a HashSet of all elements
*/
public fun <T> Iterable<T>.toHashSet() : HashSet<T> {
return toCollection(HashSet<T>())
}
/**
* Returns a HashSet of all elements
*/
public fun <T> Stream<T>.toHashSet() : HashSet<T> {
return toCollection(HashSet<T>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun <T> Array<out T>.toLinkedList() : LinkedList<T> {
return toCollection(LinkedList<T>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun BooleanArray.toLinkedList() : LinkedList<Boolean> {
return toCollection(LinkedList<Boolean>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun ByteArray.toLinkedList() : LinkedList<Byte> {
return toCollection(LinkedList<Byte>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun CharArray.toLinkedList() : LinkedList<Char> {
return toCollection(LinkedList<Char>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun DoubleArray.toLinkedList() : LinkedList<Double> {
return toCollection(LinkedList<Double>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun FloatArray.toLinkedList() : LinkedList<Float> {
return toCollection(LinkedList<Float>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun IntArray.toLinkedList() : LinkedList<Int> {
return toCollection(LinkedList<Int>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun LongArray.toLinkedList() : LinkedList<Long> {
return toCollection(LinkedList<Long>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun ShortArray.toLinkedList() : LinkedList<Short> {
return toCollection(LinkedList<Short>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun <T> Iterable<T>.toLinkedList() : LinkedList<T> {
return toCollection(LinkedList<T>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun <T> Stream<T>.toLinkedList() : LinkedList<T> {
return toCollection(LinkedList<T>())
}
/**
* Returns a List containing all elements
*/
public fun <T> Array<out T>.toList() : List<T> {
return toCollection(ArrayList<T>())
}
/**
* Returns a List containing all elements
*/
public fun BooleanArray.toList() : List<Boolean> {
val list = ArrayList<Boolean>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun ByteArray.toList() : List<Byte> {
val list = ArrayList<Byte>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun CharArray.toList() : List<Char> {
val list = ArrayList<Char>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun DoubleArray.toList() : List<Double> {
val list = ArrayList<Double>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun FloatArray.toList() : List<Float> {
val list = ArrayList<Float>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun IntArray.toList() : List<Int> {
val list = ArrayList<Int>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun LongArray.toList() : List<Long> {
val list = ArrayList<Long>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun ShortArray.toList() : List<Short> {
val list = ArrayList<Short>(size)
for (item in this) list.add(item)
return list
}
/**
* Returns a List containing all elements
*/
public fun <T> Iterable<T>.toList() : List<T> {
return toCollection(ArrayList<T>())
}
/**
* Returns a List containing all elements
*/
public fun <T> Stream<T>.toList() : List<T> {
return toCollection(ArrayList<T>())
}
/**
* Returns a Set of all elements
*/
public fun <T> Array<out T>.toSet() : Set<T> {
return toCollection(LinkedHashSet<T>())
}
/**
* Returns a Set of all elements
*/
public fun BooleanArray.toSet() : Set<Boolean> {
return toCollection(LinkedHashSet<Boolean>())
}
/**
* Returns a Set of all elements
*/
public fun ByteArray.toSet() : Set<Byte> {
return toCollection(LinkedHashSet<Byte>())
}
/**
* Returns a Set of all elements
*/
public fun CharArray.toSet() : Set<Char> {
return toCollection(LinkedHashSet<Char>())
}
/**
* Returns a Set of all elements
*/
public fun DoubleArray.toSet() : Set<Double> {
return toCollection(LinkedHashSet<Double>())
}
/**
* Returns a Set of all elements
*/
public fun FloatArray.toSet() : Set<Float> {
return toCollection(LinkedHashSet<Float>())
}
/**
* Returns a Set of all elements
*/
public fun IntArray.toSet() : Set<Int> {
return toCollection(LinkedHashSet<Int>())
}
/**
* Returns a Set of all elements
*/
public fun LongArray.toSet() : Set<Long> {
return toCollection(LinkedHashSet<Long>())
}
/**
* Returns a Set of all elements
*/
public fun ShortArray.toSet() : Set<Short> {
return toCollection(LinkedHashSet<Short>())
}
/**
* Returns a Set of all elements
*/
public fun <T> Iterable<T>.toSet() : Set<T> {
return toCollection(LinkedHashSet<T>())
}
/**
* Returns a Set of all elements
*/
public fun <T> Stream<T>.toSet() : Set<T> {
return toCollection(LinkedHashSet<T>())
}
/**
* Returns a sorted list of all elements
*/
public fun <T: Comparable<T>> Array<out T>.toSortedList() : List<T> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun BooleanArray.toSortedList() : List<Boolean> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun ByteArray.toSortedList() : List<Byte> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun CharArray.toSortedList() : List<Char> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun DoubleArray.toSortedList() : List<Double> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun FloatArray.toSortedList() : List<Float> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun IntArray.toSortedList() : List<Int> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun LongArray.toSortedList() : List<Long> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun ShortArray.toSortedList() : List<Short> {
return toArrayList().sort()
}
/**
* Returns a sorted list of all elements
*/
public fun <T: Comparable<T>> Iterable<T>.toSortedList() : List<T> {
return sort()
}
/**
* Returns a sorted list of all elements
*/
public fun <T: Comparable<T>> Stream<T>.toSortedList() : List<T> {
return toArrayList().sort()
}
/**
* Returns a SortedSet of all elements
*/
public fun <T> Array<out T>.toSortedSet() : SortedSet<T> {
return toCollection(TreeSet<T>())
}
/**
* Returns a SortedSet of all elements
*/
public fun BooleanArray.toSortedSet() : SortedSet<Boolean> {
return toCollection(TreeSet<Boolean>())
}
/**
* Returns a SortedSet of all elements
*/
public fun ByteArray.toSortedSet() : SortedSet<Byte> {
return toCollection(TreeSet<Byte>())
}
/**
* Returns a SortedSet of all elements
*/
public fun CharArray.toSortedSet() : SortedSet<Char> {
return toCollection(TreeSet<Char>())
}
/**
* Returns a SortedSet of all elements
*/
public fun DoubleArray.toSortedSet() : SortedSet<Double> {
return toCollection(TreeSet<Double>())
}
/**
* Returns a SortedSet of all elements
*/
public fun FloatArray.toSortedSet() : SortedSet<Float> {
return toCollection(TreeSet<Float>())
}
/**
* Returns a SortedSet of all elements
*/
public fun IntArray.toSortedSet() : SortedSet<Int> {
return toCollection(TreeSet<Int>())
}
/**
* Returns a SortedSet of all elements
*/
public fun LongArray.toSortedSet() : SortedSet<Long> {
return toCollection(TreeSet<Long>())
}
/**
* Returns a SortedSet of all elements
*/
public fun ShortArray.toSortedSet() : SortedSet<Short> {
return toCollection(TreeSet<Short>())
}
/**
* Returns a SortedSet of all elements
*/
public fun <T> Iterable<T>.toSortedSet() : SortedSet<T> {
return toCollection(TreeSet<T>())
}
/**
* Returns a SortedSet of all elements
*/
public fun <T> Stream<T>.toSortedSet() : SortedSet<T> {
return toCollection(TreeSet<T>())
}
@@ -0,0 +1,361 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun <T> Array<out T>.binarySearch(element: T, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun ByteArray.binarySearch(element: Byte, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun CharArray.binarySearch(element: Char, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun DoubleArray.binarySearch(element: Double, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun FloatArray.binarySearch(element: Float, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun IntArray.binarySearch(element: Int, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun LongArray.binarySearch(element: Long, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted.
*/
public fun ShortArray.binarySearch(element: Short, fromIndex: Int = 0, toIndex: Int = size - 1) : Int {
return Arrays.binarySearch(this, fromIndex, toIndex, element)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun <T> Array<out T>.copyOf(newSize: Int = size) : Array<T> {
return Arrays.copyOf(this, newSize) as Array<T>
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun BooleanArray.copyOf(newSize: Int = size) : BooleanArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun ByteArray.copyOf(newSize: Int = size) : ByteArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun CharArray.copyOf(newSize: Int = size) : CharArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun DoubleArray.copyOf(newSize: Int = size) : DoubleArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun FloatArray.copyOf(newSize: Int = size) : FloatArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun IntArray.copyOf(newSize: Int = size) : IntArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun LongArray.copyOf(newSize: Int = size) : LongArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of the riginal array
*/
public fun ShortArray.copyOf(newSize: Int = size) : ShortArray {
return Arrays.copyOf(this, newSize)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun <T> Array<out T>.copyOfRange(from: Int, to: Int) : Array<T> {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun BooleanArray.copyOfRange(from: Int, to: Int) : BooleanArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun ByteArray.copyOfRange(from: Int, to: Int) : ByteArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun CharArray.copyOfRange(from: Int, to: Int) : CharArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun DoubleArray.copyOfRange(from: Int, to: Int) : DoubleArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun FloatArray.copyOfRange(from: Int, to: Int) : FloatArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun IntArray.copyOfRange(from: Int, to: Int) : IntArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun LongArray.copyOfRange(from: Int, to: Int) : LongArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Returns new array which is a copy of range of original array
*/
public fun ShortArray.copyOfRange(from: Int, to: Int) : ShortArray {
return Arrays.copyOfRange(this, from, to)
}
/**
* Fills original array with the provided value
*/
public fun <T> Array<out T>.fill(element: T) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun BooleanArray.fill(element: Boolean) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun ByteArray.fill(element: Byte) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun CharArray.fill(element: Char) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun DoubleArray.fill(element: Double) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun FloatArray.fill(element: Float) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun IntArray.fill(element: Int) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun LongArray.fill(element: Long) : Unit {
Arrays.fill(this, element)
}
/**
* Fills original array with the provided value
*/
public fun ShortArray.fill(element: Short) : Unit {
Arrays.fill(this, element)
}
/**
* Returns a list containing all elements that are instances of specified class
*/
public fun <T, R: T> Array<out T>.filterIsInstance(klass: Class<R>) : List<R> {
return filterIsInstanceTo(ArrayList<R>(), klass)
}
/**
* Returns a list containing all elements that are instances of specified class
*/
public fun <T, R: T> Iterable<T>.filterIsInstance(klass: Class<R>) : List<R> {
return filterIsInstanceTo(ArrayList<R>(), klass)
}
/**
* Returns a stream containing all elements that are instances of specified class
*/
public fun <T, R: T> Stream<T>.filterIsInstance(klass: Class<R>) : Stream<T> {
return FilteringStream(this, true, { klass.isInstance(it) })
}
/**
* Appends all elements that are instances of specified class into the given *collection*
*/
public fun <T, C: MutableCollection<in R>, R: T> Array<out T>.filterIsInstanceTo(collection: C, klass: Class<R>) : C {
for (element in this) if (klass.isInstance(element)) collection.add(element as R)
return collection
}
/**
* Appends all elements that are instances of specified class into the given *collection*
*/
public fun <T, C: MutableCollection<in R>, R: T> Iterable<T>.filterIsInstanceTo(collection: C, klass: Class<R>) : C {
for (element in this) if (klass.isInstance(element)) collection.add(element as R)
return collection
}
/**
* Appends all elements that are instances of specified class into the given *collection*
*/
public fun <T, C: MutableCollection<in R>, R: T> Stream<T>.filterIsInstanceTo(collection: C, klass: Class<R>) : C {
for (element in this) if (klass.isInstance(element)) collection.add(element as R)
return collection
}
/**
* Sorts array or range in array inplace
*/
public fun <T> Array<out T>.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
/**
* Sorts array or range in array inplace
*/
public fun ByteArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
/**
* Sorts array or range in array inplace
*/
public fun CharArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
/**
* Sorts array or range in array inplace
*/
public fun DoubleArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
/**
* Sorts array or range in array inplace
*/
public fun FloatArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
/**
* Sorts array or range in array inplace
*/
public fun IntArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
/**
* Sorts array or range in array inplace
*/
public fun LongArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
/**
* Sorts array or range in array inplace
*/
public fun ShortArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit {
Arrays.sort(this, fromIndex, toIndex)
}
+361
View File
@@ -0,0 +1,361 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Array<out T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun BooleanArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ByteArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun CharArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun DoubleArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun FloatArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun IntArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun LongArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ShortArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Iterable<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Stream<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Array<out T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun BooleanArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ByteArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun CharArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun DoubleArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun FloatArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun IntArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun LongArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun ShortArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Iterable<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
/**
* Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied.
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
public fun <T> Stream<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
-111
View File
@@ -1,111 +0,0 @@
package kotlin
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
import java.util.Arrays
import kotlin.jvm.internal.Intrinsic
// Array "constructor"
[Intrinsic("kotlin.arrays.array")] public fun <reified T> array(vararg t : T) : Array<T> = t
// "constructors" for primitive types array
[Intrinsic("kotlin.arrays.array")] public fun doubleArray(vararg content : Double) : DoubleArray = content
[Intrinsic("kotlin.arrays.array")] public fun floatArray(vararg content : Float) : FloatArray = content
[Intrinsic("kotlin.arrays.array")] public fun longArray(vararg content : Long) : LongArray = content
[Intrinsic("kotlin.arrays.array")] public fun intArray(vararg content : Int) : IntArray = content
[Intrinsic("kotlin.arrays.array")] public fun charArray(vararg content : Char) : CharArray = content
[Intrinsic("kotlin.arrays.array")] public fun shortArray(vararg content : Short) : ShortArray = content
[Intrinsic("kotlin.arrays.array")] public fun byteArray(vararg content : Byte) : ByteArray = content
[Intrinsic("kotlin.arrays.array")] public fun booleanArray(vararg content : Boolean) : BooleanArray = content
public fun ByteArray.binarySearch(key: Byte) : Int = Arrays.binarySearch(this, key)
public fun ShortArray.binarySearch(key: Short) : Int = Arrays.binarySearch(this, key)
public fun IntArray.binarySearch(key: Int) : Int = Arrays.binarySearch(this, key)
public fun LongArray.binarySearch(key: Long) : Int = Arrays.binarySearch(this, key)
public fun FloatArray.binarySearch(key: Float) : Int = Arrays.binarySearch(this, key)
public fun DoubleArray.binarySearch(key: Double) : Int = Arrays.binarySearch(this, key)
public fun CharArray.binarySearch(key: Char) : Int = Arrays.binarySearch(this, key)
public fun ByteArray.binarySearch(fromIndex: Int, toIndex: Int, key: Byte) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public fun ShortArray.binarySearch(fromIndex: Int, toIndex: Int, key: Short) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public fun IntArray.binarySearch(fromIndex: Int, toIndex: Int, key: Int) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public fun LongArray.binarySearch(fromIndex: Int, toIndex: Int, key: Long) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public fun FloatArray.binarySearch(fromIndex: Int, toIndex: Int, key: Float) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public fun DoubleArray.binarySearch(fromIndex: Int, toIndex: Int, key: Double) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public fun CharArray.binarySearch(fromIndex: Int, toIndex: Int, key: Char) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
/*
public inline fun <T> Array<T>.binarySearch(key: T, comparator: public fun(T,T):Int) = Arrays.binarySearch(this, key, object: java.util.Comparator<T> {
public override fun compare(a: T, b: T) = comparator(a, b)
public override fun equals(obj: Any?) = obj.identityEquals(this)
})
*/
public fun BooleanArray.fill(value: Boolean) : Unit = Arrays.fill(this, value)
public fun ByteArray.fill(value: Byte) : Unit = Arrays.fill(this, value)
public fun ShortArray.fill(value: Short) : Unit = Arrays.fill(this, value)
public fun IntArray.fill(value: Int) : Unit = Arrays.fill(this, value)
public fun LongArray.fill(value: Long) : Unit = Arrays.fill(this, value)
public fun FloatArray.fill(value: Float) : Unit = Arrays.fill(this, value)
public fun DoubleArray.fill(value: Double) : Unit = Arrays.fill(this, value)
public fun CharArray.fill(value: Char) : Unit = Arrays.fill(this, value)
public fun <T: Any?> Array<T>.fill(value: T) : Unit = Arrays.fill(this, value)
public fun ByteArray.sort() : Unit = Arrays.sort(this)
public fun ShortArray.sort() : Unit = Arrays.sort(this)
public fun IntArray.sort() : Unit = Arrays.sort(this)
public fun LongArray.sort() : Unit = Arrays.sort(this)
public fun FloatArray.sort() : Unit = Arrays.sort(this)
public fun DoubleArray.sort() : Unit = Arrays.sort(this)
public fun CharArray.sort() : Unit = Arrays.sort(this)
public fun ByteArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public fun ShortArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public fun IntArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public fun LongArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public fun FloatArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public fun DoubleArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public fun CharArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public fun BooleanArray.copyOf(newLength: Int = this.size) : BooleanArray = Arrays.copyOf(this, newLength)
public fun ByteArray.copyOf(newLength: Int = this.size) : ByteArray = Arrays.copyOf(this, newLength)
public fun ShortArray.copyOf(newLength: Int = this.size) : ShortArray = Arrays.copyOf(this, newLength)
public fun IntArray.copyOf(newLength: Int = this.size) : IntArray = Arrays.copyOf(this, newLength)
public fun LongArray.copyOf(newLength: Int = this.size) : LongArray = Arrays.copyOf(this, newLength)
public fun FloatArray.copyOf(newLength: Int = this.size) : FloatArray = Arrays.copyOf(this, newLength)
public fun DoubleArray.copyOf(newLength: Int = this.size) : DoubleArray = Arrays.copyOf(this, newLength)
public fun CharArray.copyOf(newLength: Int = this.size) : CharArray = Arrays.copyOf(this, newLength)
// TODO: resuling array may contain nulls even if T is non-nullable
public fun <T> Array<T>.copyOf(newLength: Int = this.size) : Array<T> = Arrays.copyOf(this, newLength) as Array<T>
public fun BooleanArray.copyOfRange(from: Int, to: Int) : BooleanArray = Arrays.copyOfRange(this, from, to)
public fun ByteArray.copyOfRange(from: Int, to: Int) : ByteArray = Arrays.copyOfRange(this, from, to)
public fun ShortArray.copyOfRange(from: Int, to: Int) : ShortArray = Arrays.copyOfRange(this, from, to)
public fun IntArray.copyOfRange(from: Int, to: Int) : IntArray = Arrays.copyOfRange(this, from, to)
public fun LongArray.copyOfRange(from: Int, to: Int) : LongArray = Arrays.copyOfRange(this, from, to)
public fun FloatArray.copyOfRange(from: Int, to: Int) : FloatArray = Arrays.copyOfRange(this, from, to)
public fun DoubleArray.copyOfRange(from: Int, to: Int) : DoubleArray = Arrays.copyOfRange(this, from, to)
public fun CharArray.copyOfRange(from: Int, to: Int) : CharArray = Arrays.copyOfRange(this, from, to)
// TODO: resuling array may contain nulls even if T is non-nullable
public fun <T> Array<T>.copyOfRange(from: Int, to: Int) : Array<T> = Arrays.copyOfRange(this, from, to) as Array<T>
public val ByteArray.inputStream : ByteArrayInputStream
get() = ByteArrayInputStream(this)
public fun ByteArray.inputStream(offset: Int, length: Int) : ByteArrayInputStream = ByteArrayInputStream(this, offset, length)
public fun ByteArray.toString(encoding: String): String = String(this, encoding)
public fun ByteArray.toString(encoding: Charset): String = String(this, encoding)
[Intrinsic("kotlin.collections.copyToArray")] public fun <reified T> Collection<T>.copyToArray(): Array<T> =
throw UnsupportedOperationException()
+73
View File
@@ -0,0 +1,73 @@
package kotlin
import java.util.*
import java.util.concurrent.Callable
deprecated("Use firstOrNull function instead.")
public inline fun <T> Array<out T>.find(predicate: (T) -> Boolean): T? = firstOrNull(predicate)
deprecated("Use firstOrNull function instead.")
public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? = firstOrNull(predicate)
deprecated("Use listOf(...) or arrayListOf(...) instead")
public fun arrayList<T>(vararg values: T): ArrayList<T> = arrayListOf(*values)
deprecated("Use setOf(...) or hashSetOf(...) instead")
public fun hashSet<T>(vararg values: T): HashSet<T> = hashSetOf(*values)
deprecated("Use mapOf(...) or hashMapOf(...) instead")
public fun <K, V> hashMap(vararg values: Pair<K, V>): HashMap<K, V> = hashMapOf(*values)
deprecated("Use listOf(...) or linkedListOf(...) instead")
public fun linkedList<T>(vararg values: T): LinkedList<T> = linkedListOf(*values)
deprecated("Use sortedSetOf(...) instead")
public fun sortedSet<T>(vararg values: T): TreeSet<T> = sortedSetOf(*values)
deprecated("Use sortedSetOf(...) instead")
public fun sortedSet<T>(comparator: Comparator<T>, vararg values: T): TreeSet<T> = sortedSetOf(comparator, *values)
deprecated("Use sortedMapOf(...) instead")
public fun <K, V> sortedMap(vararg values: Pair<K, V>): SortedMap<K, V> = sortedMapOf(*values)
deprecated("Use linkedMapOf(...) instead")
public fun <K, V> linkedMap(vararg values: Pair<K, V>): LinkedHashMap<K, V> = linkedMapOf(*values)
/**
* A helper method for creating a [[Callable]] from a function
*/
deprecated("Use SAM constructor: Callable(...)")
public /*inline*/ fun <T> callable(action: () -> T): Callable<T> {
return object: Callable<T> {
public override fun call() = action()
}
}
/**
* A helper method for creating a [[Runnable]] from a function
*/
deprecated("Use SAM constructor: Runnable(...)")
public /*inline*/ fun runnable(action: () -> Unit): Runnable {
return object: Runnable {
public override fun run() {
action()
}
}
}
deprecated("Use withIndices() followed by forEach {}")
public inline fun <T> List<T>.forEachWithIndex(operation : (Int, T) -> Unit): Unit = withIndices().forEach {
operation(it.first, it.second)
}
deprecated("Function with undefined semantic")
public fun <T> countTo(n: Int): (T) -> Boolean {
var count = 0
return { ++count; count <= n }
}
deprecated("Use contains() function instead")
public fun <T> Iterable<T>.containsItem(item : T) : Boolean = contains(item)
deprecated("Use sortBy() instead")
public fun <T> Iterable<T>.sort(comparator: java.util.Comparator<T>) : List<T> = sortBy(comparator)
+12
View File
@@ -0,0 +1,12 @@
package kotlin
public fun <T: Any> Function1<T, T?>.toGenerator(initialValue: T): Function0<T?> {
var nextValue: T? = initialValue
return {
nextValue?.let { result ->
nextValue = this@toGenerator(result)
result
}
}
}
@@ -1,77 +0,0 @@
package kotlin
// Number of extension function for java.lang.Iterable that shouldn't participate in auto generation
import java.util.AbstractList
import java.util.Comparator
import java.util.ArrayList
/**
* Count the number of elements in collection.
*
* If base collection implements [[Collection]] interface method [[Collection.size()]] will be used.
* Otherwise, this method determines the count by iterating through the all items.
*/
public fun <T> Iterable<T>.count() : Int {
if (this is Collection<T>) {
return this.size()
}
var number : Int = 0
for (elem in this) {
++number
}
return number
}
public fun <T> countTo(n: Int): (T) -> Boolean {
var count = 0
return { ++count; count <= n }
}
/**
* Get the first element in the collection.
*
* Will throw an exception if there are no elements
*/
public fun <T> Iterable<T>.first() : T {
if (this is List<T>) {
return this.first()
}
return this.iterator().next()
}
/**
* Checks if collection contains given item.
*
* Method checks equality of the objects with T.equals method.
* If collection implements [[java.util.AbstractCollection]] an overridden implementation of the contains
* method will be used.
*/
public fun <T> Iterable<T>.containsItem(item : T) : Boolean {
if (this is java.util.AbstractCollection<T>) {
return this.contains(item);
}
for (elem in this) {
if (elem == item) {
return true
}
}
return false
}
public fun <T: Comparable<T>> Iterable<T>.sort() : List<T> {
val list = toCollection(ArrayList<T>())
java.util.Collections.sort(list)
return list
}
public fun <T> Iterable<T>.sort(comparator: java.util.Comparator<T>) : List<T> {
val list = toCollection(ArrayList<T>())
java.util.Collections.sort(list, comparator)
return list
}
-103
View File
@@ -1,103 +0,0 @@
package kotlin
import java.util.*
/** Returns the size of the collection */
public val Collection<*>.size : Int
get() = size()
/** Returns true if this collection is empty */
public val Collection<*>.empty : Boolean
get() = isEmpty()
public val Collection<*>.indices : IntRange
get() = 0..size-1
public val Int.indices: IntRange
get() = 0..this-1
/** Returns true if the collection is not empty */
public fun <T> Collection<T>.isNotEmpty() : Boolean = !this.isEmpty()
/** Returns true if this collection is not empty */
val Collection<*>.notEmpty : Boolean
get() = isNotEmpty()
/** Returns the Collection if its not null otherwise it returns the empty list */
public fun <T> Collection<T>?.orEmpty() : Collection<T> = this ?: Collections.emptyList<T>()
/** TODO these functions don't work when they generate the Array<T> versions when they are in JLIterables */
public fun <T: Comparable<T>> Iterable<T>.toSortedList() : List<T> = toCollection(ArrayList<T>()).sort()
public fun <T: Comparable<T>> Iterable<T>.toSortedList(comparator: java.util.Comparator<T>) : List<T> = toList().sort(comparator)
// List APIs
/** Returns the List if its not null otherwise returns the empty list */
public fun <T> List<T>?.orEmpty() : List<T> = this ?: Collections.emptyList<T>()
/**
TODO figure out necessary variance/generics ninja stuff... :)
public inline fun <in T> List<T>.sort(transform: fun(T) : java.lang.Comparable<*>) : List<T> {
val comparator = java.util.Comparator<T>() {
public fun compare(o1: T, o2: T): Int {
val v1 = transform(o1)
val v2 = transform(o2)
if (v1 == v2) {
return 0
} else {
return v1.compareTo(v2)
}
}
}
answer.sort(comparator)
}
*/
/**
* Returns the first item in the list or null if the list is empty
*
* @includeFunctionBody ../../test/ListTest.kt first
*/
val <T> List<T>.first : T?
get() = this.head
/**
* Returns the last item in the list or null if the list is empty
*
* @includeFunctionBody ../../test/ListTest.kt last
*/
val <T> List<T>.last : T?
get() {
val s = this.size
return if (s > 0) this.get(s - 1) else null
}
/**
* Returns the index of the last item in the list or -1 if the list is empty
*
* @includeFunctionBody ../../test/ListTest.kt lastIndex
*/
val <T> List<T>.lastIndex : Int
get() = this.size - 1
/**
* Returns the first item in the list or null if the list is empty
*
* @includeFunctionBody ../../test/ListTest.kt head
*/
val <T> List<T>.head : T?
get() = if (this.isNotEmpty()) this.get(0) else null
/**
* Returns all elements in this collection apart from the first one
*
* @includeFunctionBody ../../test/ListTest.kt tail
*/
val <T> List<T>.tail : List<T>
get() {
return this.drop(1)
}
-114
View File
@@ -1,114 +0,0 @@
package kotlin
import java.util.*
/** Returns a new read-only list of given elements */
public fun listOf<T>(vararg values: T): List<T> = arrayListOf(*values)
/** Returns a new read-only set of given elements */
public fun setOf<T>(vararg values: T): Set<T> = values.toCollection(LinkedHashSet<T>())
/** Returns a new read-only map of given pairs, where the first value is the key, and the second is value */
public fun mapOf<K, V>(vararg values: Pair<K, V>): Map<K, V> = hashMapOf(*values)
/** Returns a new ArrayList with a variable number of initial elements */
public fun arrayListOf<T>(vararg values: T) : ArrayList<T> = values.toCollection(ArrayList<T>(values.size))
deprecated("Use listOf(...) or arrayListOf(...) instead")
public fun arrayList<T>(vararg values: T) : ArrayList<T> = arrayListOf(*values)
/** Returns a new LinkedList with a variable number of initial elements */
public fun linkedListOf<T>(vararg values: T) : LinkedList<T> = values.toCollection(LinkedList<T>())
deprecated("Use listOf(...) or linkedListOf(...) instead")
public fun linkedList<T>(vararg values: T) : LinkedList<T> = linkedListOf(*values)
/** Returns a new HashSet with a variable number of initial elements */
public fun hashSetOf<T>(vararg values: T) : HashSet<T> = values.toCollection(HashSet<T>(values.size))
deprecated("Use setOf(...) or hashSetOf(...) instead")
public fun hashSet<T>(vararg values: T) : HashSet<T> = hashSetOf(*values)
/**
* Returns a new [[SortedSet]] with the initial elements
*/
public fun sortedSetOf<T>(vararg values: T) : TreeSet<T> = values.toCollection(TreeSet<T>())
deprecated("Use sortedSetOf(...) instead")
public fun sortedSet<T>(vararg values: T) : TreeSet<T> = sortedSetOf(*values)
/**
* Returns a new [[SortedSet]] with the given *comparator* and the initial elements
*/
public fun sortedSetOf<T>(comparator: Comparator<T>, vararg values: T) : TreeSet<T> = values.toCollection(TreeSet<T>(comparator))
deprecated("Use sortedSetOf(...) instead")
public fun sortedSet<T>(comparator: Comparator<T>, vararg values: T) : TreeSet<T> = sortedSetOf(comparator, *values)
/**
* Returns a new [[HashMap]] populated with the given pairs where the first value in each pair
* is the key and the second value is the value
*
* @includeFunctionBody ../../test/MapTest.kt createUsingPairs
*/
public fun <K,V> hashMapOf(vararg values: Pair<K,V>): HashMap<K,V> {
val answer = HashMap<K,V>(values.size)
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v.first, v.second)
}
return answer
}
deprecated("Use mapOf(...) or hashMapOf(...) instead")
public fun <K,V> hashMap(vararg values: Pair<K,V>): HashMap<K,V> = hashMapOf(*values)
/**
* Returns a new [[SortedMap]] populated with the given pairs where the first value in each pair
* is the key and the second value is the value
*
* @includeFunctionBody ../../test/MapTest.kt createSortedMap
*/
public fun <K,V> sortedMapOf(vararg values: Pair<K, V>): SortedMap<K,V> {
val answer = TreeMap<K,V>()
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v.first, v.second)
}
return answer
}
deprecated("Use sortedMapOf(...) instead")
public fun <K,V> sortedMap(vararg values: Pair<K, V>): SortedMap<K,V> = sortedMapOf(*values)
/**
* Returns a new [[LinkedHashMap]] populated with the given pairs where the first value in each pair
* is the key and the second value is the value. This map preserves insertion order so iterating through
* the map's entries will be in the same order
*
* @includeFunctionBody ../../test/MapTest.kt createLinkedMap
*/
public fun <K,V> linkedMapOf(vararg values: Pair<K, V>): LinkedHashMap<K,V> {
val answer = LinkedHashMap<K,V>(values.size)
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v.first, v.second)
}
return answer
}
deprecated("Use linkedMapOf(...) instead")
public fun <K,V> linkedMap(vararg values: Pair<K, V>): LinkedHashMap<K,V> = linkedMapOf(*values)
/** Returns the Set if its not null otherwise returns the empty set */
public fun <T> Set<T>?.orEmpty() : Set<T>
= if (this != null) this else Collections.EMPTY_SET as Set<T>
-82
View File
@@ -1,82 +0,0 @@
package kotlin
/**
* Get the first element in the list or throws [[EmptyIterableException]] if list is empty.
*/
public fun <T> List<T>.first() : T {
return if (size() > 0) get(0) else throw EmptyIterableException(this)
}
/**
* Get the first element in the list or *null* if list is empty.
*/
public fun <T:Any> List<T>.firstOrNull() : T? {
return if (size() > 0) get(0) else null
}
/**
* Get the last element in the list or throws [[EmptyIterableException]] if list is empty.
*/
public fun <T> List<T>.last() : T {
val s = size()
return if (s > 0) get(s - 1) else throw EmptyIterableException(this)
}
/**
* Get the last element in the list or *null* if list is empty.
*/
public fun <T:Any> List<T>.lastOrNull() : T? {
val s = size()
return if (s > 0) get(s - 1) else null
}
public inline fun <T> List<T>.forEachWithIndex(operation : (Int, T) -> Unit) {
for (index in indices) {
operation(index, get(index))
}
}
/**
* Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements
*/
public inline fun <T, R> List<T>.foldRight(initial: R, operation: (T, R) -> R) : R {
var r = initial
var index = size - 1
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*/
public inline fun <T> List<T>.reduceRight(operation: (T, T) -> T) : T {
var index = size - 1
if (index < 0) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var r = get(index--)
while (index >= 0) {
r = operation(get(index--), r)
}
return r
}
/**
* Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T:Any> List<T?>.requireNoNulls() : List<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this")
}
}
return this as List<T>
}
@@ -1,15 +0,0 @@
package kotlin
/**
* Adds all elements of the given *iterator* to this [[MutableCollection]]
*/
public fun <T> MutableCollection<T>.addAll(iterator: Iterator<T>): Unit {
for (e in iterator) add(e)
}
/**
* Adds all elements of the given *iterable* to this [[MutableCollection]]
*/
public fun <T> MutableCollection<T>.addAll(iterable: Iterable<T>): Unit {
for (e in iterable) add(e)
}
+7 -46
View File
@@ -1,63 +1,24 @@
package kotlin
import java.util.ArrayList
import java.util.HashSet
import java.util.LinkedList
/**
Helper to make java.util.Enumeration usable in for
*/
public fun <T> java.util.Enumeration<T>.iterator(): Iterator<T> = object: Iterator<T> {
override fun hasNext(): Boolean = hasMoreElements()
public override fun next() : T = nextElement()
}
/*
* Extension functions on the standard Kotlin types to behave like the java.lang.* and java.util.* collections
*/
/**
Add iterated elements to given container
*/
/*
public fun <T,U: Collection<in T>> Iterator<T>.toCollection(container: U) : U {
while(hasNext())
container.add(next())
return container
}
*/
/**
Add iterated elements to java.util.ArrayList
*/
public fun <T> Iterator<T>.toArrayList() : ArrayList<T> = toCollection(ArrayList<T>())
/**
Add iterated elements to java.util.HashSet
*/
public fun <T> Iterator<T>.toHashSet() : HashSet<T> = toCollection(HashSet<T>())
/**
* Creates a tuple of type [[Pair<A,B>]] from this and *that* which can be useful for creating [[Map]] literals
* with less noise, for example
* @includeFunctionBody ../../test/MapTest.kt createUsingTo
* @includeFunctionBody ../../test/collections/MapTest.kt createUsingTo
*/
public fun <A,B> A.to(that: B): Pair<A, B> = Pair(this, that)
public fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
/**
Run function f
*/
public inline fun <T> run(f: () -> T) : T = f()
*/
public inline fun <T> run(f: () -> T): T = f()
/**
* Execute f with given receiver
*/
public inline fun <T, R> with(receiver: T, f: T.() -> R) : R = receiver.f()
public inline fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
/**
* Converts receiver to body parameter
*/
public inline fun <T:Any, R> T.let(f: (T) -> R): R = f(this)
*/
public inline fun <T : Any, R> T.let(f: (T) -> R): R = f(this)
+1 -41
View File
@@ -1,26 +1,7 @@
package kotlin
import java.util.ArrayList
import java.util.LinkedList
import java.util.HashSet
import java.util.LinkedHashSet
import java.util.TreeSet
import java.util.SortedSet
import java.util.Comparator
import java.io.PrintWriter
import java.io.PrintStream
import java.util.concurrent.Callable
/**
* Add iterated elements to a [[LinkedHashSet]] to preserve insertion order
*/
public fun <T> Iterator<T>.toLinkedSet() : LinkedHashSet<T> = toCollection(LinkedHashSet<T>())
/**
* Add iterated elements to [[SortedSet]] with the given *comparator* to ensure iteration is in the order of the given comparator
*/
public fun <T> Iterator<T>.toSortedSet(comparator: Comparator<T>) : SortedSet<T> = toCollection(TreeSet<T>(comparator))
/**
* Allows a stack trace to be printed from Kotlin's [[Throwable]]
@@ -42,29 +23,8 @@ public fun Throwable.printStackTrace(stream: PrintStream): Unit {
* Returns the stack trace
*/
public fun Throwable.getStackTrace() : Array<StackTraceElement> {
public fun Throwable.getStackTrace(): Array<StackTraceElement> {
val jlt = this as java.lang.Throwable
return jlt.getStackTrace()!!
}
/**
* A helper method for creating a [[Callable]] from a function
*/
deprecated("Use SAM constructor: Callable(...)")
public /*inline*/ fun <T> callable(action: ()-> T): Callable<T> {
return object: Callable<T> {
public override fun call() = action()
}
}
/**
* A helper method for creating a [[Runnable]] from a function
*/
deprecated("Use SAM constructor: Runnable(...)")
public /*inline*/ fun runnable(action: ()-> Unit): Runnable {
return object: Runnable {
public override fun run() {
action()
}
}
}
@@ -1,11 +1,5 @@
package kotlin
/** Returns true if the array is not empty */
public fun <T> Array<out T>.isNotEmpty() : Boolean = !this.isEmpty()
/** Returns true if the array is empty */
public fun <T> Array<out T>.isEmpty() : Boolean = this.size == 0
public val BooleanArray.lastIndex : Int
get() = this.size - 1
@@ -0,0 +1,37 @@
package kotlin
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
import java.util.Arrays
import kotlin.jvm.internal.Intrinsic
// Array "constructor"
[Intrinsic("kotlin.arrays.array")] public fun <reified T> array(vararg t : T) : Array<T> = t
// "constructors" for primitive types array
[Intrinsic("kotlin.arrays.array")] public fun doubleArray(vararg content : Double) : DoubleArray = content
[Intrinsic("kotlin.arrays.array")] public fun floatArray(vararg content : Float) : FloatArray = content
[Intrinsic("kotlin.arrays.array")] public fun longArray(vararg content : Long) : LongArray = content
[Intrinsic("kotlin.arrays.array")] public fun intArray(vararg content : Int) : IntArray = content
[Intrinsic("kotlin.arrays.array")] public fun charArray(vararg content : Char) : CharArray = content
[Intrinsic("kotlin.arrays.array")] public fun shortArray(vararg content : Short) : ShortArray = content
[Intrinsic("kotlin.arrays.array")] public fun byteArray(vararg content : Byte) : ByteArray = content
[Intrinsic("kotlin.arrays.array")] public fun booleanArray(vararg content : Boolean) : BooleanArray = content
public val ByteArray.inputStream : ByteArrayInputStream
get() = ByteArrayInputStream(this)
public fun ByteArray.inputStream(offset: Int, length: Int) : ByteArrayInputStream = ByteArrayInputStream(this, offset, length)
public fun ByteArray.toString(encoding: String): String = String(this, encoding)
public fun ByteArray.toString(encoding: Charset): String = String(this, encoding)
[Intrinsic("kotlin.collections.copyToArray")] public fun <reified T> Collection<T>.copyToArray(): Array<T> =
throw UnsupportedOperationException()
@@ -0,0 +1,15 @@
package kotlin
/**
Helper to make java.util.Enumeration usable in for
*/
public fun <T> java.util.Enumeration<T>.iterator(): Iterator<T> = object: Iterator<T> {
override fun hasNext(): Boolean = hasMoreElements()
public override fun next() : T = nextElement()
}
/**
* Returns the given iterator itself. This allows to use an instance of iterator in a ranged for-loop
*/
public fun <T> Iterator<T>.iterator(): Iterator<T> = this
@@ -0,0 +1,120 @@
package kotlin
import java.util.*
/** Returns a new read-only list of given elements */
public fun listOf<T>(vararg values: T): List<T> = arrayListOf(*values)
/** Returns a new read-only map of given pairs, where the first value is the key, and the second is value */
public fun mapOf<K, V>(vararg values: Pair<K, V>): Map<K, V> = hashMapOf(*values)
/** Returns a new ArrayList with a variable number of initial elements */
public fun arrayListOf<T>(vararg values: T): ArrayList<T> = values.toCollection(ArrayList<T>(values.size))
/** Returns a new HashSet with a variable number of initial elements */
public fun hashSetOf<T>(vararg values: T): HashSet<T> = values.toCollection(HashSet<T>(values.size))
/**
* Returns a new [[HashMap]] populated with the given pairs where the first value in each pair
* is the key and the second value is the value
*
* @includeFunctionBody ../../test/collections/MapTest.kt createUsingPairs
*/
public fun <K, V> hashMapOf(vararg values: Pair<K, V>): HashMap<K, V> {
val answer = HashMap<K, V>(values.size)
answer.putAll(*values)
return answer
}
/** Returns the size of the collection */
public val Collection<*>.size: Int
get() = size()
/** Returns true if this collection is empty */
public val Collection<*>.empty: Boolean
get() = isEmpty()
public val Collection<*>.indices: IntRange
get() = 0..size - 1
public val Int.indices: IntRange
get() = 0..this - 1
/** Returns true if the collection is not empty */
public fun <T> Collection<T>.isNotEmpty(): Boolean = !this.isEmpty()
/** Returns true if this collection is not empty */
val Collection<*>.notEmpty: Boolean
get() = isNotEmpty()
/** Returns the Collection if its not null otherwise it returns the empty list */
public fun <T> Collection<T>?.orEmpty(): Collection<T> = this ?: Collections.emptyList<T>()
// List APIs
/** Returns the List if its not null otherwise returns the empty list */
public fun <T> List<T>?.orEmpty(): List<T> = this ?: Collections.emptyList<T>()
/**
TODO figure out necessary variance/generics ninja stuff... :)
public inline fun <in T> List<T>.sort(transform: fun(T) : java.lang.Comparable<*>) : List<T> {
val comparator = java.util.Comparator<T>() {
public fun compare(o1: T, o2: T): Int {
val v1 = transform(o1)
val v2 = transform(o2)
if (v1 == v2) {
return 0
} else {
return v1.compareTo(v2)
}
}
}
answer.sort(comparator)
}
*/
/**
* Returns the first item in the list or null if the list is empty
*
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt first
*/
val <T> List<T>.first: T?
get() = this.head
/**
* Returns the last item in the list or null if the list is empty
*
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt last
*/
val <T> List<T>.last: T?
get() {
val s = this.size
return if (s > 0) this.get(s - 1) else null
}
/**
* Returns the index of the last item in the list or -1 if the list is empty
*
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt lastIndex
*/
val <T> List<T>.lastIndex: Int
get() = this.size - 1
/**
* Returns the first item in the list or null if the list is empty
*
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt head
*/
val <T> List<T>.head: T?
get() = if (this.isNotEmpty()) this.get(0) else null
/**
* Returns all elements in this collection apart from the first one
*
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt tail
*/
val <T> List<T>.tail: List<T>
get() {
return this.drop(1)
}
@@ -0,0 +1,60 @@
package kotlin
import java.util.*
/** Returns a new read-only set of given elements */
public fun setOf<T>(vararg values: T): Set<T> = values.toCollection(LinkedHashSet<T>())
/** Returns a new LinkedList with a variable number of initial elements */
public fun linkedListOf<T>(vararg values: T): LinkedList<T> = values.toCollection(LinkedList<T>())
/**
* Returns a new [[SortedSet]] with the initial elements
*/
public fun sortedSetOf<T>(vararg values: T): TreeSet<T> = values.toCollection(TreeSet<T>())
/**
* Returns a new [[SortedSet]] with the given *comparator* and the initial elements
*/
public fun sortedSetOf<T>(comparator: Comparator<T>, vararg values: T): TreeSet<T> = values.toCollection(TreeSet<T>(comparator))
/**
* Returns a new [[SortedMap]] populated with the given pairs where the first value in each pair
* is the key and the second value is the value
*
* @includeFunctionBody ../../test/collections/MapTest.kt createSortedMap
*/
public fun <K, V> sortedMapOf(vararg values: Pair<K, V>): SortedMap<K, V> {
val answer = TreeMap<K, V>()
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v.first, v.second)
}
return answer
}
/**
* Returns a new [[LinkedHashMap]] populated with the given pairs where the first value in each pair
* is the key and the second value is the value. This map preserves insertion order so iterating through
* the map's entries will be in the same order
*
* @includeFunctionBody ../../test/collections/MapTest.kt createLinkedMap
*/
public fun <K, V> linkedMapOf(vararg values: Pair<K, V>): LinkedHashMap<K, V> {
val answer = LinkedHashMap<K, V>(values.size)
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v.first, v.second)
}
return answer
}
/** Returns the Set if its not null otherwise returns the empty set */
public fun <T> Set<T>?.orEmpty(): Set<T>
= if (this != null) this else Collections.EMPTY_SET as Set<T>
@@ -42,7 +42,7 @@ fun <K,V> Map.Entry<K,V>.component2() : V {
/**
* Returns the value for the given key or returns the result of the defaultValue function if there was no entry for the given key
*
* @includeFunctionBody ../../test/MapTest.kt getOrElse
* @includeFunctionBody ../../test/collections/MapTest.kt getOrElse
*/
public inline fun <K,V> Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V {
if (this.containsKey(key)) {
@@ -55,7 +55,7 @@ public inline fun <K,V> Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V {
/**
* Returns the value for the given key or the result of the defaultValue function is put into the map for the given value and returned
*
* @includeFunctionBody ../../test/MapTest.kt getOrElse
* @includeFunctionBody ../../test/collections/MapTest.kt getOrPut
*/
public inline fun <K,V> MutableMap<K,V>.getOrPut(key: K, defaultValue: ()-> V) : V {
if (this.containsKey(key)) {
@@ -71,23 +71,13 @@ public inline fun <K,V> MutableMap<K,V>.getOrPut(key: K, defaultValue: ()-> V) :
/**
* Returns an [[Iterator]] over the entries in the [[Map]]
*
* @includeFunctionBody ../../test/MapTest.kt iterateWithProperties
* @includeFunctionBody ../../test/collections/MapTest.kt iterateWithProperties
*/
public fun <K,V> Map<K,V>.iterator(): Iterator<Map.Entry<K,V>> {
val entrySet = this.entrySet()
return entrySet.iterator()
}
/**
* Transforms each [[Map.Entry]] in this [[Map]] with the given *transform* function and
* adds each return value to the given *results* collection
*/
public inline fun <K,V,R, C: MutableCollection<in R>> Map<K,V>.mapTo(result: C, transform: (Map.Entry<K,V>) -> R) : C {
for (item in this)
result.add(transform(item))
return result
}
/**
* Populates the given *result* [[Map]] with the value returned by applying the *transform* function on each [[Map.Entry]] in this [[Map]]
*/
@@ -116,19 +106,10 @@ public fun <K,V> Map<K,V>.toMap(map: MutableMap<K,V>): Map<K,V> {
return map
}
/**
* Returns a new List containing the results of applying the given *transform* function to each [[Map.Entry]] in this [[Map]]
*
* @includeFunctionBody ../../test/CollectionTest.kt map
*/
public inline fun <K,V,R> Map<K,V>.map(transform: (Map.Entry<K,V>) -> R) : List<R> {
return mapTo(java.util.ArrayList<R>(this.size), transform)
}
/**
* Returns a new Map containing the results of applying the given *transform* function to each [[Map.Entry]] in this [[Map]]
*
* @includeFunctionBody ../../test/MapTest.kt mapValues
* @includeFunctionBody ../../test/collections/MapTest.kt mapValues
*/
public inline fun <K,V,R> Map<K,V>.mapValues(transform : (Map.Entry<K,V>) -> R): Map<K,R> {
return mapValuesTo(java.util.HashMap<K,R>(this.size), transform)
@@ -16,7 +16,7 @@ public fun <K,V> Map<K,V>.toLinkedMap(): LinkedHashMap<K,V> = toMap<K,V>(LinkedH
/**
* Converts this [[Map]] to a [[SortedMap]] so iteration order will be in key order
*
* @includeFunctionBody ../../test/MapTest.kt toSortedMap
* @includeFunctionBody ../../test/collections/MapTest.kt toSortedMap
*/
public fun <K,V> Map<K,V>.toSortedMap(): SortedMap<K,V> = toMap<K,V>(TreeMap()) as SortedMap<K,V>
@@ -24,7 +24,7 @@ public fun <K,V> Map<K,V>.toSortedMap(): SortedMap<K,V> = toMap<K,V>(TreeMap())
* Converts this [[Map]] to a [[SortedMap]] using the given *comparator* so that iteration order will be in the order
* defined by the comparator
*
* @includeFunctionBody ../../test/MapTest.kt toSortedMapWithComparator
* @includeFunctionBody ../../test/collections/MapTest.kt toSortedMapWithComparator
*/
public fun <K,V> Map<K,V>.toSortedMap(comparator: Comparator<K>): SortedMap<K,V> = toMap<K,V>(TreeMap(comparator)) as SortedMap<K,V>
@@ -32,7 +32,7 @@ public fun <K,V> Map<K,V>.toSortedMap(comparator: Comparator<K>): SortedMap<K,V>
/**
* Converts this [[Map]] to a [[Properties]] object
*
* @includeFunctionBody ../../test/MapTest.kt toProperties
* @includeFunctionBody ../../test/collections/MapTest.kt toProperties
*/
public fun Map<String, String>.toProperties(): Properties {
val answer = Properties()
@@ -0,0 +1,16 @@
package kotlin
/**
* Adds all elements of the given *iterable* to this [[MutableCollection]]
*/
public fun <T> MutableCollection<in T>.addAll(iterable: Iterable<T>): Unit {
for (e in iterable) add(e)
}
public fun <T> MutableCollection<in T>.addAll(stream: Stream<T>): Unit {
for (e in stream) add(e)
}
public fun <T> MutableCollection<in T>.addAll(array: Array<T>): Unit {
for (e in array) add(e)
}
@@ -0,0 +1,132 @@
package kotlin
import kotlin.support.AbstractIterator
public trait Stream<out T> {
public fun iterator(): Iterator<T>
}
public fun <T> Iterable<T>.stream(): Stream<T> = object : Stream<T> {
override fun iterator(): Iterator<T> {
return this@stream.iterator()
}
}
public class FilteringStream<T>(val stream: Stream<T>, val sendWhen: Boolean = true, val predicate: (T) -> Boolean) : Stream<T> {
override fun iterator(): Iterator<T> = object : AbstractIterator<T>() {
val iterator = stream.iterator()
override fun computeNext() {
while (iterator.hasNext()) {
val item = iterator.next()
if (predicate(item) == sendWhen) {
setNext(item)
return
}
}
done()
}
}
}
public class TransformingStream<T, R>(val stream: Stream<T>, val transformer: (T) -> R) : Stream<R> {
override fun iterator(): Iterator<R> = object : AbstractIterator<R>() {
val iterator = stream.iterator()
override fun computeNext() {
if (iterator.hasNext()) {
setNext(transformer(iterator.next()))
} else {
done()
}
}
}
}
class ZippingStream<T1, T2>(val stream1: Stream<T1>, val stream2: Stream<T2>) : Stream<Pair<T1,T2>> {
override fun iterator(): Iterator<Pair<T1,T2>> = object : AbstractIterator<Pair<T1,T2>>() {
val iterator1 = stream1.iterator()
val iterator2 = stream2.iterator()
override fun computeNext() {
if (iterator1.hasNext() && iterator2.hasNext()) {
setNext(iterator1.next() to iterator2.next())
} else {
done()
}
}
}
}
public class FlatteningStream<T, R>(val stream: Stream<T>, val transformer: (T) -> Stream<R>) : Stream<R> {
override fun iterator(): Iterator<R> = object : AbstractIterator<R>() {
val iterator = stream.iterator()
var itemIterator: Iterator<R>? = null
override fun computeNext() {
while (itemIterator == null) {
if (!iterator.hasNext()) {
done()
break;
} else {
val element = iterator.next()
val nextItemIterator = transformer(element).iterator()
if (nextItemIterator.hasNext())
itemIterator = nextItemIterator
}
}
val currentItemIterator = itemIterator
if (currentItemIterator == null) {
done()
} else {
setNext(currentItemIterator.next())
if (!currentItemIterator.hasNext())
itemIterator = null
}
}
}
}
public class LimitedStream<T>(val stream: Stream<T>, val stopWhen: Boolean = true, val predicate: (T) -> Boolean) : Stream<T> {
override fun iterator(): Iterator<T> = object : AbstractIterator<T>() {
val iterator = stream.iterator()
override fun computeNext() {
if (!iterator.hasNext()) {
done()
} else {
val item = iterator.next()
if (predicate(item) == stopWhen) {
done()
} else {
setNext(item)
}
}
}
}
}
public class FunctionStream<T : Any>(val producer: () -> T?) : Stream<T> {
override fun iterator(): Iterator<T> = object : AbstractIterator<T>() {
override fun computeNext() {
val item = producer()
if (item == null) {
done()
} else {
setNext(item)
}
}
}
}
/**
* Returns a stream which invokes the function to calculate the next value on each iteration until the function returns *null*
*/
public fun <T : Any> stream(nextFunction: () -> T?): Stream<T> {
return FunctionStream(nextFunction)
}
/**
* Returns a stream which invokes the function to calculate the next value based on the previous one on each iteration
* until the function returns *null*
*/
public /*inline*/ fun <T : Any> stream(initialValue: T, nextFunction: (T) -> T?): Stream<T> =
stream(nextFunction.toGenerator(initialValue))
@@ -4,14 +4,10 @@ import kotlin.support.*
import java.util.Collections
import kotlin.test.assertTrue
/**
* Returns the given iterator itself. This allows to use an instance of iterator in a ranged for-loop
*/
public fun <T> Iterator<T>.iterator(): Iterator<T> = this
/**
* Returns an iterator which invokes the function to calculate the next value on each iteration until the function returns *null*
*/
deprecated("Use streams for lazy collection operations.")
public fun <T:Any> iterate(nextFunction: () -> T?) : Iterator<T> {
return FunctionIterator(nextFunction)
}
@@ -20,19 +16,23 @@ public fun <T:Any> iterate(nextFunction: () -> T?) : Iterator<T> {
* Returns an iterator which invokes the function to calculate the next value based on the previous one on each iteration
* until the function returns *null*
*/
deprecated("Use streams for lazy collection operations.")
public /*inline*/ fun <T: Any> iterate(initialValue: T, nextFunction: (T) -> T?): Iterator<T> =
iterate(nextFunction.toGenerator(initialValue))
/**
* Returns an iterator whose values are pairs composed of values produced by given pair of iterators
*/
deprecated("Use streams for lazy collection operations.")
public fun <T, S> Iterator<T>.zip(iterator: Iterator<S>): Iterator<Pair<T, S>> = PairIterator(this, iterator)
/**
* Returns an iterator shifted to right by the given number of elements
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.skip(n: Int): Iterator<T> = SkippingIterator(this, n)
deprecated("Use streams for lazy collection operations.")
class FilterIterator<T>(val iterator : Iterator<T>, val predicate: (T)-> Boolean) : AbstractIterator<T>() {
override protected fun computeNext(): Unit {
while (iterator.hasNext()) {
@@ -46,6 +46,7 @@ class FilterIterator<T>(val iterator : Iterator<T>, val predicate: (T)-> Boolean
}
}
deprecated("Use streams for lazy collection operations.")
class FilterNotNullIterator<T:Any>(val iterator : Iterator<T?>?) : AbstractIterator<T>() {
override protected fun computeNext(): Unit {
if (iterator != null) {
@@ -61,6 +62,7 @@ class FilterNotNullIterator<T:Any>(val iterator : Iterator<T?>?) : AbstractItera
}
}
deprecated("Use streams for lazy collection operations.")
class MapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> R) : AbstractIterator<R>() {
override protected fun computeNext() : Unit {
if (iterator.hasNext()) {
@@ -71,6 +73,7 @@ class MapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> R) : A
}
}
deprecated("Use streams for lazy collection operations.")
class FlatMapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> Iterator<R>) : AbstractIterator<R>() {
var transformed: Iterator<R> = iterate<R> { null }
@@ -90,6 +93,7 @@ class FlatMapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> It
}
}
deprecated("Use streams for lazy collection operations.")
class TakeWhileIterator<T>(val iterator: Iterator<T>, val predicate: (T) -> Boolean) : AbstractIterator<T>() {
override protected fun computeNext() : Unit {
if (iterator.hasNext()) {
@@ -104,6 +108,7 @@ class TakeWhileIterator<T>(val iterator: Iterator<T>, val predicate: (T) -> Bool
}
/** An [[Iterator]] which invokes a function to calculate the next value in the iteration until the function returns *null* */
deprecated("Use streams for lazy collection operations.")
class FunctionIterator<T:Any>(val nextFunction: () -> T?): AbstractIterator<T>() {
override protected fun computeNext(): Unit {
@@ -117,8 +122,10 @@ class FunctionIterator<T:Any>(val nextFunction: () -> T?): AbstractIterator<T>()
}
/** An [[Iterator]] which iterates over a number of iterators in sequence */
deprecated("Use streams for lazy collection operations.")
fun CompositeIterator<T>(vararg iterators: Iterator<T>): CompositeIterator<T> = CompositeIterator(iterators.iterator())
deprecated("Use streams for lazy collection operations.")
class CompositeIterator<T>(val iterators: Iterator<Iterator<T>>): AbstractIterator<T>() {
var currentIter: Iterator<T>? = null
@@ -147,6 +154,7 @@ class CompositeIterator<T>(val iterators: Iterator<Iterator<T>>): AbstractIterat
}
/** A singleton [[Iterator]] which invokes once over a value */
deprecated("Use streams for lazy collection operations.")
class SingleIterator<T>(val value: T): AbstractIterator<T>() {
var first = true
@@ -160,6 +168,7 @@ class SingleIterator<T>(val value: T): AbstractIterator<T>() {
}
}
deprecated("Use streams for lazy collection operations.")
class IndexIterator<T>(val iterator : Iterator<T>): Iterator<Pair<Int, T>> {
private var index : Int = 0
@@ -172,6 +181,7 @@ class IndexIterator<T>(val iterator : Iterator<T>): Iterator<Pair<Int, T>> {
}
}
deprecated("Use streams for lazy collection operations.")
public class PairIterator<T, S>(
val iterator1 : Iterator<T>, val iterator2 : Iterator<S>
): AbstractIterator<Pair<T, S>>() {
@@ -185,6 +195,7 @@ public class PairIterator<T, S>(
}
}
deprecated("Use streams for lazy collection operations.")
class SkippingIterator<T>(val iterator: Iterator<T>, val n: Int): Iterator<T> {
private var firstTime: Boolean = true
@@ -208,13 +219,3 @@ class SkippingIterator<T>(val iterator: Iterator<T>, val n: Int): Iterator<T> {
return iterator.hasNext()
}
}
public fun <T: Any> Function1<T, T?>.toGenerator(initialValue: T): Function0<T?> {
var nextValue: T? = initialValue
return {
nextValue?.let { result ->
nextValue = this@toGenerator(result)
result
}
}
}
@@ -3,8 +3,10 @@ package kotlin
import kotlin.support.*
/** Returns an iterator over elements that are instances of a given type *R* which is a subclass of *T* */
deprecated("Use streams for lazy collection operations.")
public fun <T, R: T> Iterator<T>.filterIsInstance(klass: Class<R>): Iterator<R> = FilterIsIterator<T,R>(this, klass)
deprecated("Use streams for lazy collection operations.")
private class FilterIsIterator<T, R :T>(val iterator : Iterator<T>, val klass: Class<R>) : AbstractIterator<R>() {
override protected fun computeNext(): Unit {
while (iterator.hasNext()) {
@@ -10,6 +10,7 @@ import java.util.*
/**
* Returns *true* if all elements match the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.all(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
@@ -18,6 +19,7 @@ public inline fun <T> Iterator<T>.all(predicate: (T) -> Boolean) : Boolean {
/**
* Returns *true* if any elements match the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.any(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
@@ -28,6 +30,7 @@ public inline fun <T> Iterator<T>.any(predicate: (T) -> Boolean) : Boolean {
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
@@ -45,6 +48,7 @@ public fun <T> Iterator<T>.appendString(buffer: Appendable, separator: String =
/**
* Returns the number of elements which match the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.count(predicate: (T) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
@@ -54,6 +58,7 @@ public inline fun <T> Iterator<T>.count(predicate: (T) -> Boolean) : Int {
/**
* Returns a list containing everything but the first *n* elements
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.drop(n: Int) : List<T> {
return dropWhile(countTo(n))
}
@@ -61,6 +66,7 @@ public fun <T> Iterator<T>.drop(n: Int) : List<T> {
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.dropWhile(predicate: (T) -> Boolean) : List<T> {
return dropWhileTo(ArrayList<T>(), predicate)
}
@@ -68,6 +74,7 @@ public inline fun <T> Iterator<T>.dropWhile(predicate: (T) -> Boolean) : List<T>
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, L: MutableList<in T>> Iterator<T>.dropWhileTo(result: L, predicate: (T) -> Boolean) : L {
var start = true
for (element in this) {
@@ -84,6 +91,7 @@ public inline fun <T, L: MutableList<in T>> Iterator<T>.dropWhileTo(result: L, p
/**
* Returns an iterator over elements which match the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.filter(predicate: (T) -> Boolean) : Iterator<T> {
return FilterIterator<T>(this, predicate)
}
@@ -91,6 +99,7 @@ public fun <T> Iterator<T>.filter(predicate: (T) -> Boolean) : Iterator<T> {
/**
* Returns an iterator over elements which don't match the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.filterNot(predicate: (T) -> Boolean) : Iterator<T> {
return filter {!predicate(it)}
}
@@ -98,6 +107,7 @@ public inline fun <T> Iterator<T>.filterNot(predicate: (T) -> Boolean) : Iterato
/**
* Returns an iterator over non-*null* elements
*/
deprecated("Use streams for lazy collection operations.")
public fun <T:Any> Iterator<T?>.filterNotNull() : Iterator<T> {
return FilterNotNullIterator(this)
}
@@ -105,6 +115,7 @@ public fun <T:Any> Iterator<T?>.filterNotNull() : Iterator<T> {
/**
* Filters all non-*null* elements into the given list
*/
deprecated("Use streams for lazy collection operations.")
public fun <T:Any, C: MutableCollection<in T>> Iterator<T?>.filterNotNullTo(result: C) : C {
for (element in this) if (element != null) result.add(element)
return result
@@ -113,6 +124,7 @@ public fun <T:Any, C: MutableCollection<in T>> Iterator<T?>.filterNotNullTo(resu
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterNotTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
@@ -121,6 +133,7 @@ public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterNotTo(result
/**
* Filters all elements which match the given predicate into the given list
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
@@ -129,6 +142,7 @@ public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterTo(result: C
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T:Any> Iterator<T>.find(predicate: (T) -> Boolean) : T? {
for (element in this) if (predicate(element)) return element
return null
@@ -137,6 +151,7 @@ public inline fun <T:Any> Iterator<T>.find(predicate: (T) -> Boolean) : T? {
/**
* Returns an iterator over the concatenated results of transforming each element to one or more values
*/
deprecated("Use streams for lazy collection operations.")
public fun <T, R> Iterator<T>.flatMap(transform: (T) -> Iterator<R>) : Iterator<R> {
return FlatMapIterator<T, R>(this, transform)
}
@@ -144,6 +159,7 @@ public fun <T, R> Iterator<T>.flatMap(transform: (T) -> Iterator<R>) : Iterator<
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.flatMapTo(result: C, transform: (T) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
@@ -155,6 +171,7 @@ public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.flatMapTo(resul
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, R> Iterator<T>.fold(initial: R, operation: (R, T) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
@@ -164,6 +181,7 @@ public inline fun <T, R> Iterator<T>.fold(initial: R, operation: (R, T) -> R) :
/**
* Performs the given *operation* on each element
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit) : Unit {
for (element in this) operation(element)
}
@@ -171,10 +189,12 @@ public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit) : Unit {
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, K> Iterator<T>.groupBy(toKey: (T) -> K) : Map<K, List<T>> {
return groupByTo(HashMap<K, MutableList<T>>(), toKey)
}
deprecated("Use streams for lazy collection operations.")
public inline fun <T, K> Iterator<T>.groupByTo(result: MutableMap<K, MutableList<T>>, toKey: (T) -> K) : Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
@@ -189,15 +209,19 @@ public inline fun <T, K> Iterator<T>.groupByTo(result: MutableMap<K, MutableList
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
return buffer.toString()
}
// -------------------------
/**
* Returns an iterator obtained by applying *transform*, a function transforming an object of type *T* into an object of type *R*
*/
deprecated("Use streams for lazy collection operations.")
public fun <T, R> Iterator<T>.map(transform : (T) -> R) : Iterator<R> {
return MapIterator<T, R>(this, transform)
}
@@ -206,6 +230,7 @@ public fun <T, R> Iterator<T>.map(transform : (T) -> R) : Iterator<R> {
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
@@ -215,9 +240,10 @@ public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.mapTo(result: C
/**
* Returns the largest element or null if there are no elements
*/
deprecated("Use streams for lazy collection operations.")
public fun <T: Comparable<T>> Iterator<T>.max() : T? {
if (!hasNext()) return null
var max = next()
while (hasNext()) {
val e = next()
@@ -229,9 +255,10 @@ public fun <T: Comparable<T>> Iterator<T>.max() : T? {
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <R: Comparable<R>, T: Any> Iterator<T>.maxBy(f: (T) -> R) : T? {
if (!hasNext()) return null
var maxElem = next()
var maxValue = f(maxElem)
while (hasNext()) {
@@ -248,9 +275,10 @@ public inline fun <R: Comparable<R>, T: Any> Iterator<T>.maxBy(f: (T) -> R) : T?
/**
* Returns the smallest element or null if there are no elements
*/
deprecated("Use streams for lazy collection operations.")
public fun <T: Comparable<T>> Iterator<T>.min() : T? {
if (!hasNext()) return null
var min = next()
while (hasNext()) {
val e = next()
@@ -262,9 +290,10 @@ public fun <T: Comparable<T>> Iterator<T>.min() : T? {
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <R: Comparable<R>, T: Any> Iterator<T>.minBy(f: (T) -> R) : T? {
if (!hasNext()) return null
var minElem = next()
var minValue = f(minElem)
while (hasNext()) {
@@ -281,6 +310,7 @@ public inline fun <R: Comparable<R>, T: Any> Iterator<T>.minBy(f: (T) -> R) : T?
/**
* Partitions this collection into a pair of collections
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.partition(predicate: (T) -> Boolean) : Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
@@ -297,6 +327,7 @@ public inline fun <T> Iterator<T>.partition(predicate: (T) -> Boolean) : Pair<Li
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.plus(collection: Iterable<T>) : Iterator<T> {
return plus(collection.iterator())
}
@@ -304,6 +335,7 @@ public fun <T> Iterator<T>.plus(collection: Iterable<T>) : Iterator<T> {
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.plus(element: T) : Iterator<T> {
return CompositeIterator<T>(this, SingleIterator(element))
}
@@ -311,6 +343,7 @@ public fun <T> Iterator<T>.plus(element: T) : Iterator<T> {
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.plus(iterator: Iterator<T>) : Iterator<T> {
return CompositeIterator<T>(this, iterator)
}
@@ -319,23 +352,25 @@ public fun <T> Iterator<T>.plus(iterator: Iterator<T>) : Iterator<T> {
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T> Iterator<T>.reduce(operation: (T, T) -> T) : T {
val iterator = this.iterator()
if (!iterator.hasNext()) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: T = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext()) {
result = operation(result, iterator.next())
}
return result
}
/**
* Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
deprecated("Use streams for lazy collection operations.")
public fun <T:Any> Iterator<T?>.requireNoNulls() : Iterator<T> {
return map<T?, T>{
if (it == null) throw IllegalArgumentException("null element in iterator $this") else it
@@ -345,6 +380,7 @@ public fun <T:Any> Iterator<T?>.requireNoNulls() : Iterator<T> {
/**
* Reverses the order the elements into a list
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.reverse() : List<T> {
val list = toCollection(ArrayList<T>())
Collections.reverse(list)
@@ -355,6 +391,7 @@ public fun <T> Iterator<T>.reverse() : List<T> {
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, R: Comparable<R>> Iterator<T>.sortBy(f: (T) -> R) : List<T> {
val sortedList = toCollection(ArrayList<T>())
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) ->
@@ -369,6 +406,7 @@ public inline fun <T, R: Comparable<R>> Iterator<T>.sortBy(f: (T) -> R) : List<T
/**
* Returns an iterator restricted to the first *n* elements
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.take(n: Int) : Iterator<T> {
var count = n
return takeWhile{ --count >= 0 }
@@ -377,6 +415,7 @@ public fun <T> Iterator<T>.take(n: Int) : Iterator<T> {
/**
* Returns an iterator restricted to the first elements that match the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.takeWhile(predicate: (T) -> Boolean) : Iterator<T> {
return TakeWhileIterator<T>(this, predicate)
}
@@ -384,6 +423,7 @@ public fun <T> Iterator<T>.takeWhile(predicate: (T) -> Boolean) : Iterator<T> {
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
deprecated("Use streams for lazy collection operations.")
public inline fun <T, C: MutableCollection<in T>> Iterator<T>.takeWhileTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
@@ -392,6 +432,7 @@ public inline fun <T, C: MutableCollection<in T>> Iterator<T>.takeWhileTo(result
/**
* Copies all elements into the given collection
*/
deprecated("Use streams for lazy collection operations.")
public fun <T, C: MutableCollection<in T>> Iterator<T>.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
@@ -400,6 +441,7 @@ public fun <T, C: MutableCollection<in T>> Iterator<T>.toCollection(result: C) :
/**
* Copies all elements into a [[LinkedList]]
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.toLinkedList() : LinkedList<T> {
return toCollection(LinkedList<T>())
}
@@ -407,20 +449,39 @@ public fun <T> Iterator<T>.toLinkedList() : LinkedList<T> {
/**
* Copies all elements into a [[List]]
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.toList() : List<T> {
return toCollection(ArrayList<T>())
}
/**
* Copies all elements into a [[ArrayList]]
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.toArrayList() : ArrayList<T> {
return toCollection(ArrayList<T>())
}
/**
* Copies all elements into a [[Set]]
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.toSet() : Set<T> {
return toCollection(LinkedHashSet<T>())
}
/**
* Copies all elements into a [[HashSet]]
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.toHashSet() : HashSet<T> {
return toCollection(HashSet<T>())
}
/**
* Copies all elements into a [[SortedSet]]
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.toSortedSet() : SortedSet<T> {
return toCollection(TreeSet<T>())
}
@@ -428,6 +489,7 @@ public fun <T> Iterator<T>.toSortedSet() : SortedSet<T> {
/**
* Returns an iterator of Pairs(index, data)
*/
deprecated("Use streams for lazy collection operations.")
public fun <T> Iterator<T>.withIndices() : Iterator<Pair<Int, T>> {
return IndexIterator(iterator())
}
+24 -22
View File
@@ -153,7 +153,7 @@ fun Document?.get(selector: String): List<Element> {
val id = selector.substring(1)
val element = this?.getElementById(id)
return if (element != null)
arrayList<Element>(element)
arrayListOf(element)
else
emptyElementList()
} else {
@@ -174,7 +174,7 @@ fun Element.get(selector: String): List<Element> {
} else if (selector.startsWith("#")) {
val element = this.ownerDocument?.getElementById(selector.substring(1))
return if (element != null)
arrayList<Element>(element)
arrayListOf(element)
else
emptyElementList()
} else {
@@ -259,33 +259,35 @@ fun Node.clear(): Unit {
}
/** Returns an [[Iterator]] over the next siblings of this node */
fun Node.nextSiblings() : Iterator<Node> = NextSiblingIterator(this)
fun Node.nextSiblings() : Iterable<Node> = NextSiblings(this)
class NextSiblingIterator(var node: Node) : AbstractIterator<Node>() {
override fun computeNext(): Unit {
val nextValue = node.nextSibling
if (nextValue != null) {
setNext(nextValue)
node = nextValue
} else {
done()
class NextSiblings(var node: Node) : Iterable<Node> {
override fun iterator(): Iterator<Node> = object : AbstractIterator<Node>() {
override fun computeNext(): Unit {
val nextValue = node.nextSibling
if (nextValue != null) {
setNext(nextValue)
node = nextValue
} else {
done()
}
}
}
}
/** Returns an [[Iterator]] over the next siblings of this node */
fun Node.previousSiblings() : Iterator<Node> = PreviousSiblingIterator(this)
fun Node.previousSiblings() : Iterable<Node> = PreviousSiblings(this)
class PreviousSiblingIterator(var node: Node) : AbstractIterator<Node>() {
override fun computeNext(): Unit {
val nextValue = node.previousSibling
if (nextValue != null) {
setNext(nextValue)
node = nextValue
} else {
done()
class PreviousSiblings(var node: Node) : Iterable<Node> {
override fun iterator(): Iterator<Node> = object : AbstractIterator<Node>() {
override fun computeNext(): Unit {
val nextValue = node.previousSibling
if (nextValue != null) {
setNext(nextValue)
node = nextValue
} else {
done()
}
}
}
}
+2 -2
View File
@@ -112,10 +112,10 @@ public val NodeList.outerHTML: String
get() = toList().map { it.innerHTML }.makeString("")
/** Returns an [[Iterator]] of all the next [[Element]] siblings */
fun Node.nextElements(): Iterator<Element> = nextSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
fun Node.nextElements(): List<Element> = nextSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
/** Returns an [[Iterator]] of all the previous [[Element]] siblings */
fun Node.previousElements(): Iterator<Element> = previousSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
fun Node.previousElements(): List<Element> = previousSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
var Element.classSet : MutableSet<String>
@@ -0,0 +1,31 @@
package kotlin
import java.io.Closeable
/** Uses the given resource then closes it down correctly whether an exception is thrown or not */
public inline fun <T : Closeable, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this.close()
} catch (closeException: Exception) {
// eat the closeException as we are already throwing the original cause
// and we don't want to mask the real exception
// TODO on Java 7 we should call
// e.addSuppressed(closeException)
// to work like try-with-resources
// http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions
}
throw e
} finally {
if (!closed) {
this.close()
}
}
}
+3 -3
View File
@@ -92,21 +92,21 @@ public fun File.reader(): FileReader = FileReader(this)
* This method is not recommended on huge files.
*/
public fun File.readBytes(): ByteArray {
return FileInputStream(this).use<FileInputStream,ByteArray>{ it.readBytes(this.length().toInt()) }
return FileInputStream(this).use { it.readBytes(this.length().toInt()) }
}
/**
* Writes the bytes as the contents of the file
*/
public fun File.writeBytes(data: ByteArray): Unit {
return FileOutputStream(this).use<FileOutputStream,Unit>{ it.write(data) }
return FileOutputStream(this).use { it.write(data) }
}
/**
* Appends bytes to the contents of the file.
*/
public fun File.appendBytes(data: ByteArray): Unit {
return FileOutputStream(this, true).use<FileOutputStream, Unit>{ it.write(data) }
return FileOutputStream(this, true).use { it.write(data) }
}
/**
+81 -91
View File
@@ -17,84 +17,84 @@ public val defaultCharset: Charset = Charset.forName("UTF-8")!!
/** Prints the given message to [[System.out]] */
public fun print(message : Any?) {
public fun print(message: Any?) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Int) {
public fun print(message: Int) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Long) {
public fun print(message: Long) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Byte) {
public fun print(message: Byte) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Short) {
public fun print(message: Short) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Char) {
public fun print(message: Char) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Boolean) {
public fun print(message: Boolean) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Float) {
public fun print(message: Float) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : Double) {
public fun print(message: Double) {
System.out.print(message)
}
/** Prints the given message to [[System.out]] */
public fun print(message : CharArray) {
public fun print(message: CharArray) {
System.out.print(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Any?) {
public fun println(message: Any?) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Int) {
public fun println(message: Int) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Long) {
public fun println(message: Long) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Byte) {
public fun println(message: Byte) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Short) {
public fun println(message: Short) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Char) {
public fun println(message: Char) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Boolean) {
public fun println(message: Boolean) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Float) {
public fun println(message: Float) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : Double) {
public fun println(message: Double) {
System.out.println(message)
}
/** Prints the given message and newline to [[System.out]] */
public fun println(message : CharArray) {
public fun println(message: CharArray) {
System.out.println(message)
}
/** Prints a newline t[[System.out]] */
@@ -102,8 +102,11 @@ public fun println() {
System.out.println()
}
private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : InputStream() {
public override fun read() : Int {
// Since System.in can change its value on the course of program running,
// we should always delegate to current value and cannot just pass it to InputStreamReader constructor.
// We could use "by" implementation, but we can only use "by" with traits and InputStream is abstract class.
private val stdin: BufferedReader = BufferedReader(InputStreamReader(object : InputStream() {
public override fun read(): Int {
return System.`in`.read()
}
@@ -141,80 +144,62 @@ private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : I
}))
/** Reads a line of input from [[System.in]] */
public fun readLine() : String? = stdin.readLine()
/** Uses the given resource then closes it down correctly whether an exception is thrown or not */
public inline fun <T: Closeable, R> T.use(block: (T)-> R) : R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this.close()
} catch (closeException: Exception) {
// eat the closeException as we are already throwing the original cause
// and we don't want to mask the real exception
// TODO on Java 7 we should call
// e.addSuppressed(closeException)
// to work like try-with-resources
// http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions
}
throw e
} finally {
if (!closed) {
this.close()
}
}
}
public fun readLine(): String? = stdin.readLine()
/** Returns an [Iterator] of bytes over an input stream */
public fun InputStream.iterator() : ByteIterator =
object: ByteIterator() {
override fun hasNext() : Boolean = available() > 0
public fun InputStream.iterator(): ByteIterator =
object: ByteIterator() {
override fun hasNext(): Boolean = available() > 0
public override fun nextByte() : Byte = read().toByte()
}
public override fun nextByte(): Byte = read().toByte()
}
/** Creates a buffered input stream */
public fun InputStream.buffered(bufferSize: Int = defaultBufferSize) : InputStream
= if (this is BufferedInputStream)
public fun InputStream.buffered(bufferSize: Int = defaultBufferSize): InputStream
= if (this is BufferedInputStream)
this
else
BufferedInputStream(this, bufferSize)
public fun InputStream.reader(encoding: Charset = defaultCharset) : InputStreamReader = InputStreamReader(this, encoding)
/** Creates a reader on an input stream with specified *encoding* */
public fun InputStream.reader(encoding: Charset = defaultCharset): InputStreamReader = InputStreamReader(this, encoding)
public fun InputStream.reader(encoding: String) : InputStreamReader = InputStreamReader(this, encoding)
/** Creates a reader on an input stream with specified *encoding* */
public fun InputStream.reader(encoding: String): InputStreamReader = InputStreamReader(this, encoding)
public fun InputStream.reader(encoding: CharsetDecoder) : InputStreamReader = InputStreamReader(this, encoding)
/** Creates a reader on an input stream with specified *encoding* */
public fun InputStream.reader(encoding: CharsetDecoder): InputStreamReader = InputStreamReader(this, encoding)
public fun OutputStream.buffered(bufferSize: Int = defaultBufferSize) : BufferedOutputStream
= if (this is BufferedOutputStream) this else BufferedOutputStream(this, bufferSize)
/** Creates a buffered output stream */
public fun OutputStream.buffered(bufferSize: Int = defaultBufferSize): BufferedOutputStream
= if (this is BufferedOutputStream) this else BufferedOutputStream(this, bufferSize)
public fun OutputStream.writer(encoding: Charset = defaultCharset) : OutputStreamWriter = OutputStreamWriter(this, encoding)
/** Creates a writer on an output stream with specified *encoding* */
public fun OutputStream.writer(encoding: Charset = defaultCharset): OutputStreamWriter = OutputStreamWriter(this, encoding)
public fun OutputStream.writer(encoding: String) : OutputStreamWriter = OutputStreamWriter(this, encoding)
/** Creates a writer on an output stream with specified *encoding* */
public fun OutputStream.writer(encoding: String): OutputStreamWriter = OutputStreamWriter(this, encoding)
public fun OutputStream.writer(encoding: CharsetEncoder) : OutputStreamWriter = OutputStreamWriter(this, encoding)
/** Creates a writer on an output stream with specified *encoding* */
public fun OutputStream.writer(encoding: CharsetEncoder): OutputStreamWriter = OutputStreamWriter(this, encoding)
/** Creates a buffered reader, or returns self if Reader is already buffered */
public fun Reader.buffered(bufferSize: Int = defaultBufferSize): BufferedReader
= if(this is BufferedReader) this else BufferedReader(this, bufferSize)
= if (this is BufferedReader) this else BufferedReader(this, bufferSize)
/** Creates a buffered writer, or returns self if Writer is already buffered */
public fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter
= if(this is BufferedWriter) this else BufferedWriter(this, bufferSize)
= if (this is BufferedWriter) this else BufferedWriter(this, bufferSize)
/**
* Iterates through each line of this reader then closing the [[Reader]] when its completed
*/
public inline fun Reader.forEachLine(block: (String) -> Unit): Unit = useLines { lines -> lines.forEach(block) }
public fun Reader.forEachLine(block: (String) -> Unit): Unit = useLines { lines -> lines.forEach(block) }
public inline fun <T> Reader.useLines(block: (Iterator<String>) -> T): T =
this.buffered().use<BufferedReader, T>{ block(it.lineIterator()) }
public inline fun <T> Reader.useLines(block: (Stream<String>) -> T): T =
this.buffered().use { block(it.lines()) }
/**
* Returns an iterator over each line.
@@ -224,33 +209,38 @@ public inline fun <T> Reader.useLines(block: (Iterator<String>) -> T): T =
* <br>
* We suggest you try the method useLines() instead which closes the stream when the processing is complete.
*/
public fun BufferedReader.lineIterator() : Iterator<String> = LineIterator(this)
public fun BufferedReader.lines(): Stream<String> = LinesStream(this)
class LineIterator(val reader: BufferedReader) : Iterator<String> {
private var nextValue: String? = null
private var done = false
deprecated("Use lines() function which returns Stream<String>")
public fun BufferedReader.lineIterator(): Iterator<String> = lines().iterator()
override fun hasNext(): Boolean {
if (nextValue == null && !done) {
nextValue = reader.readLine()
if (nextValue == null) done = true
class LinesStream(val reader: BufferedReader) : Stream<String> {
override fun iterator(): Iterator<String> {
return object : Iterator<String> {
private var nextValue: String? = null
private var done = false
override fun hasNext(): Boolean {
if (nextValue == null && !done) {
nextValue = reader.readLine()
if (nextValue == null) done = true
}
return nextValue != null
}
public override fun next(): String {
if (!hasNext()) {
throw NoSuchElementException()
}
val answer = nextValue
nextValue = null
return answer!!
}
}
return nextValue != null
}
public override fun next(): String {
if (!hasNext()) {
throw NoSuchElementException()
}
val answer = nextValue
nextValue = null
return answer!!
}
}
/**
* Reads this stream completely into a byte array
*
@@ -326,5 +316,5 @@ public fun URL.readText(encoding: Charset): String = readBytes().toString(encodi
*
* This method is not recommended on huge files.
*/
public fun URL.readBytes(): ByteArray = this.openStream()!!.use<InputStream,ByteArray>{ it.readBytes() }
public fun URL.readBytes(): ByteArray = this.openStream()!!.use<InputStream, ByteArray>{ it.readBytes() }
+1 -1
View File
@@ -31,7 +31,7 @@ public var asserter: Asserter
if (_asserter == null) {
val klass = javaClass<Asserter>()
val loader = ServiceLoader.load(klass)
for (a in loader.iterator()) {
for (a in loader) {
if (a != null) {
_asserter = a
break
@@ -21,7 +21,7 @@ public fun Char.isJavaLetterOrDigit(): Boolean = Character.isJavaLetterOrDigit(t
/**
* Returns true if the character is whitespace
*
* @includeFunctionBody ../../test/StringTest.kt count
* @includeFunctionBody ../../test/text/StringTest.kt count
*/
public fun Char.isWhitespace(): Boolean = Character.isWhitespace(this)
@@ -8,6 +8,12 @@ import java.util.LinkedList
/** Returns the string with leading and trailing text matching the given string removed */
public fun String.trim(text: String) : String = trimLeading(text).trimTrailing(text)
/** Returns the first character */
public fun String.first() : Char = this[0]
/** Returns the last character */
public fun String.last() : Char = this[length - 1]
/** Returns the string with the prefix and postfix text trimmed */
public fun String.trim(prefix: String, postfix: String) : String = trimLeading(prefix).trimTrailing(postfix)
@@ -55,7 +61,7 @@ get() = this.length
/**
* Counts the number of characters which match the given predicate
*
* @includeFunctionBody ../../test/StringTest.kt count
* @includeFunctionBody ../../test/text/StringTest.kt count
*/
public inline fun String.count(predicate: (Char) -> Boolean): Int {
var answer = 0
@@ -176,7 +176,7 @@ get() = length()
/**
* Returns a copy of this string capitalised if it is not empty or already starting with an uppper case letter, otherwise returns this
*
* @includeFunctionBody ../../test/StringTest.kt capitalize
* @includeFunctionBody ../../test/text/StringTest.kt capitalize
*/
public fun String.capitalize(): String {
return if (isNotEmpty() && charAt(0).isLowerCase()) substring(0, 1).toUpperCase() + substring(1) else this
@@ -185,7 +185,7 @@ public fun String.capitalize(): String {
/**
* Returns a copy of this string with the first letter lower case if it is not empty or already starting with a lower case letter, otherwise returns this
*
* @includeFunctionBody ../../test/StringTest.kt decapitalize
* @includeFunctionBody ../../test/text/StringTest.kt decapitalize
*/
public fun String.decapitalize(): String {
return if (isNotEmpty() && charAt(0).isUpperCase()) substring(0, 1).toLowerCase() + substring(1) else this
@@ -194,7 +194,7 @@ public fun String.decapitalize(): String {
/**
* Repeats a given string n times.
* When n < 0, IllegalArgumentException is thrown.
* @includeFunctionBody ../../test/StringTest.kt repeat
* @includeFunctionBody ../../test/text/StringTest.kt repeat
*/
public fun String.repeat(n: Int): String {
require(n >= 0, { "Cannot repeat string $n times" })
@@ -209,14 +209,14 @@ public fun String.repeat(n: Int): String {
/**
* Filters characters which match the given predicate into new String object
*
* @includeFunctionBody ../../test/StringTest.kt filter
* @includeFunctionBody ../../test/text/StringTest.kt filter
*/
public inline fun String.filter(predicate: (Char) -> Boolean): String = filterTo(StringBuilder(), predicate).toString()
/**
* Returns an Appendable containing all characters which match the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt filter
* @includeFunctionBody ../../test/text/StringTest.kt filter
*/
public inline fun <T: Appendable> String.filterTo(result: T, predicate: (Char) -> Boolean): T
{
@@ -227,14 +227,14 @@ public inline fun <T: Appendable> String.filterTo(result: T, predicate: (Char) -
/**
* Filters characters which match the given predicate into new String object
*
* @includeFunctionBody ../../test/StringTest.kt filterNot
* @includeFunctionBody ../../test/text/StringTest.kt filterNot
*/
public inline fun String.filterNot(predicate: (Char) -> Boolean): String = filterNotTo(StringBuilder(), predicate).toString()
/**
* Returns an Appendable containing all characters which do not match the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt filterNot
* @includeFunctionBody ../../test/text/StringTest.kt filterNot
*/
public inline fun <T: Appendable> String.filterNotTo(result: T, predicate: (Char) -> Boolean): T {
for (element in this) if (!predicate(element)) result.append(element)
@@ -244,21 +244,21 @@ public inline fun <T: Appendable> String.filterNotTo(result: T, predicate: (Char
/**
* Reverses order of characters in a string
*
* @includeFunctionBody ../../test/StringTest.kt reverse
* @includeFunctionBody ../../test/text/StringTest.kt reverse
*/
public fun String.reverse(): String = StringBuilder(this).reverse().toString()
/**
* Performs the given *operation* on each character
*
* @includeFunctionBody ../../test/StringTest.kt forEach
* @includeFunctionBody ../../test/text/StringTest.kt forEach
*/
public inline fun String.forEach(operation: (Char) -> Unit) { for(c in this) operation(c) }
/**
* Returns *true* if all characters match the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt all
* @includeFunctionBody ../../test/text/StringTest.kt all
*/
public inline fun String.all(predicate: (Char) -> Boolean): Boolean {
for(c in this) if(!predicate(c)) return false
@@ -268,7 +268,7 @@ public inline fun String.all(predicate: (Char) -> Boolean): Boolean {
/**
* Returns *true* if any character matches the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt any
* @includeFunctionBody ../../test/text/StringTest.kt any
*/
public inline fun String.any(predicate: (Char) -> Boolean): Boolean {
for (c in this) if (predicate(c)) return true
@@ -281,7 +281,7 @@ public inline fun String.any(predicate: (Char) -> Boolean): Boolean {
* If a string could be huge you can specify a non-negative value of *limit* which will only show substring then it will
* a special *truncated* separator (which defaults to "..."
*
* @includeFunctionBody ../../test/StringTest.kt appendString
* @includeFunctionBody ../../test/text/StringTest.kt appendString
*/
public fun String.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
buffer.append(prefix)
@@ -297,7 +297,7 @@ public fun String.appendString(buffer: Appendable, separator: String = ", ", pre
/**
* Returns the first character which matches the given *predicate* or *null* if none matched
*
* @includeFunctionBody ../../test/StringTest.kt find
* @includeFunctionBody ../../test/text/StringTest.kt find
*/
public inline fun String.find(predicate: (Char) -> Boolean): Char? {
for (c in this) if (predicate(c)) return c
@@ -307,7 +307,7 @@ public inline fun String.find(predicate: (Char) -> Boolean): Char? {
/**
* Returns the first character which does not match the given *predicate* or *null* if none matched
*
* @includeFunctionBody ../../test/StringTest.kt findNot
* @includeFunctionBody ../../test/text/StringTest.kt findNot
*/
public inline fun String.findNot(predicate: (Char) -> Boolean): Char? {
for (c in this) if (!predicate(c)) return c
@@ -317,7 +317,7 @@ public inline fun String.findNot(predicate: (Char) -> Boolean): Char? {
/**
* Partitions this string into a pair of string
*
* @includeFunctionBody ../../test/StringTest.kt partition
* @includeFunctionBody ../../test/text/StringTest.kt partition
*/
public inline fun String.partition(predicate: (Char) -> Boolean): Pair<String, String> {
val first = StringBuilder()
@@ -351,14 +351,14 @@ public inline fun <R, C: MutableCollection<in R>> String.mapTo(result: C, transf
/**
* Returns the result of transforming each character to one or more values which are concatenated together into a single list
*
* @includeFunctionBody ../../test/StringTest.kt flatMap
* @includeFunctionBody ../../test/text/StringTest.kt flatMap
*/
public inline fun <R> String.flatMap(transform: (Char) -> Collection<R>): Collection<R> = flatMapTo(ArrayList<R>(), transform)
/**
* Returns the result of transforming each character to one or more values which are concatenated together into a passed list
*
* @includeFunctionBody ../../test/StringTest.kt flatMap
* @includeFunctionBody ../../test/text/StringTest.kt flatMap
*/
public inline fun <R> String.flatMapTo(result: MutableCollection<R>, transform: (Char) -> Collection<R>): Collection<R> {
for (c in this) result.addAll(transform(c))
@@ -368,7 +368,7 @@ public inline fun <R> String.flatMapTo(result: MutableCollection<R>, transform:
/**
* Folds all characters from left to right with the *initial* value to perform the operation on sequential pairs of characters
*
* @includeFunctionBody ../../test/StringTest.kt fold
* @includeFunctionBody ../../test/text/StringTest.kt fold
*/
public inline fun <R> String.fold(initial: R, operation: (R, Char) -> R): R {
var answer = initial
@@ -379,7 +379,7 @@ public inline fun <R> String.fold(initial: R, operation: (R, Char) -> R): R {
/**
* Folds all characters from right to left with the *initial* value to perform the operation on sequential pairs of characters
*
* @includeFunctionBody ../../test/StringTest.kt foldRight
* @includeFunctionBody ../../test/text/StringTest.kt foldRight
*/
public inline fun <R> String.foldRight(initial: R, operation: (Char, R) -> R): R = reverse().fold(initial, { x, y -> operation(y, x) })
@@ -387,7 +387,7 @@ public inline fun <R> String.foldRight(initial: R, operation: (Char, R) -> R): R
* Applies binary operation to all characters in a string, going from left to right.
* Similar to fold function, but uses the first character as initial value
*
* @includeFunctionBody ../../test/StringTest.kt reduce
* @includeFunctionBody ../../test/text/StringTest.kt reduce
*/
public inline fun String.reduce(operation: (Char, Char) -> Char): Char {
val iterator = this.iterator()
@@ -407,7 +407,7 @@ public inline fun String.reduce(operation: (Char, Char) -> Char): Char {
* Applies binary operation to all characters in a string, going from right to left.
* Similar to foldRight function, but uses the last character as initial value
*
* @includeFunctionBody ../../test/StringTest.kt reduceRight
* @includeFunctionBody ../../test/text/StringTest.kt reduceRight
*/
public inline fun String.reduceRight(operation: (Char, Char) -> Char): Char = reverse().reduce { x, y -> operation(y, x) }
@@ -415,14 +415,14 @@ public inline fun String.reduceRight(operation: (Char, Char) -> Char): Char = re
/**
* Groups the characters in the string into a new [[Map]] using the supplied *toKey* function to calculate the key to group the characters by
*
* @includeFunctionBody ../../test/StringTest.kt groupBy
* @includeFunctionBody ../../test/text/StringTest.kt groupBy
*/
public inline fun <K> String.groupBy(toKey: (Char) -> K): Map<K, String> = groupByTo<K>(HashMap<K, String>(), toKey)
/**
* Groups the characters in the string into the given [[Map]] using the supplied *toKey* function to calculate the key to group the characters by
*
* @includeFunctionBody ../../test/StringTest.kt groupBy
* @includeFunctionBody ../../test/text/StringTest.kt groupBy
*/
public inline fun <K> String.groupByTo(result: MutableMap<K, String>, toKey: (Char) -> K): Map<K, String> {
for (c in this) {
@@ -439,7 +439,7 @@ public inline fun <K> String.groupByTo(result: MutableMap<K, String>, toKey: (Ch
* If a string could be huge you can specify a non-negative value of *limit* which will only show a substring then it will
* a special *truncated* separator (which defaults to "..."
*
* @includeFunctionBody ../../test/StringTest.kt makeString
* @includeFunctionBody ../../test/text/StringTest.kt makeString
*/
public fun String.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
val buffer = StringBuilder()
@@ -450,7 +450,7 @@ public fun String.makeString(separator: String = ", ", prefix: String = "", post
/**
* Returns an Appendable containing the everything but the first characters that satisfy the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt dropWhile
* @includeFunctionBody ../../test/text/StringTest.kt dropWhile
*/
public inline fun <T: Appendable> String.dropWhileTo(result: T, predicate: (Char) -> Boolean): T {
var start = true
@@ -468,21 +468,21 @@ public inline fun <T: Appendable> String.dropWhileTo(result: T, predicate: (Char
/**
* Returns a new String containing the everything but the first characters that satisfy the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt dropWhile
* @includeFunctionBody ../../test/text/StringTest.kt dropWhile
*/
public inline fun String.dropWhile(predicate: (Char) -> Boolean): String = dropWhileTo(StringBuilder(), predicate).toString()
/**
* Returns a string containing everything but the first *n* characters
*
* @includeFunctionBody ../../test/StringTest.kt drop
* @includeFunctionBody ../../test/text/StringTest.kt drop
*/
public fun String.drop(n: Int): String = dropWhile(countTo(n))
public fun String.drop(n: Int): String = substring(Math.min(length, n))
/**
* Returns an Appendable containing the first characters that satisfy the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt takeWhile
* @includeFunctionBody ../../test/text/StringTest.kt takeWhile
*/
public inline fun <T: Appendable> String.takeWhileTo(result: T, predicate: (Char) -> Boolean): T {
for (c in this) if (predicate(c)) result.append(c) else break
@@ -492,16 +492,16 @@ public inline fun <T: Appendable> String.takeWhileTo(result: T, predicate: (Char
/**
* Returns a new String containing the first characters that satisfy the given *predicate*
*
* @includeFunctionBody ../../test/StringTest.kt takeWhile
* @includeFunctionBody ../../test/text/StringTest.kt takeWhile
*/
public inline fun String.takeWhile(predicate: (Char) -> Boolean): String = takeWhileTo(StringBuilder(), predicate).toString()
/**
* Returns a string containing the first *n* characters
*
* @includeFunctionBody ../../test/StringTest.kt take
* @includeFunctionBody ../../test/text/StringTest.kt take
*/
public fun String.take(n: Int): String = takeWhile(countTo(n))
public fun String.take(n: Int): String = substring(0, Math.min(length, n))
/** Copies all characters into the given collection */
public fun <C: MutableCollection<in Char>> String.toCollection(result: C): C {
@@ -1,35 +0,0 @@
package test.apicheck
import kotlin.util.*
import java.util.*
trait Traversable<T> {
/** Returns true if any elements in the collection match the given predicate */
fun any(predicate: (T)-> Boolean) : Boolean
/** Returns true if all elements in the collection match the given predicate */
fun all(predicate: (T)-> Boolean) : Boolean
/** Returns the first item in the collection which matches the given predicate or null if none matched */
fun find(predicate: (T)-> Boolean) : T?
/** Returns a new collection containing all elements in this collection which match the given predicate */
// TODO using: Collection<T> for the return type - I wonder if this exact type could be
// deduced somewhat from the This.Type; e.g. returning Set on a Set, Array on Array etc
fun filter(predicate: (T)-> Boolean) : Collection<T>
/** Performs the given operation on each element inside the collection */
fun forEach(operation: (element: T)-> Unit)
/** Returns a new collection containing the results of applying the given function to each element in this collection */
fun <T, R> Iterable<T>.map(transform : (T)-> R) : Collection<R>
}
/**
TODO try use delegation here to make sure we implement all the methods in the Traversable API
class ListImpl<T>(coll: ArrayList<out T>) : Traversable<T> by coll {
}
*/
-124
View File
@@ -1,124 +0,0 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionJVMTest {
test fun flatMap() {
val data = arrayList("", "foo", "bar", "x", "")
val characters = data.flatMap<String,Char>{ it.toCharList() }
println("Got list of characters ${characters}")
assertEquals(7, characters.size())
val text = characters.makeString("")
assertEquals("foobarx", text)
}
// TODO would be nice to avoid the <String>
test fun filterIntoLinkedList() {
val data = arrayList("foo", "bar")
val foo = data.filterTo(linkedList<String>()){it.startsWith("f")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(linkedList("foo"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterNotIntoLinkedList() {
val data = arrayList("foo", "bar")
val foo = data.filterNotTo(linkedList<String>()){it.startsWith("f")}
assertTrue {
foo.all{!it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(linkedList("bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterNotNullIntoLinkedList() {
val data = arrayList(null, "foo", null, "bar")
val foo = data.filterNotNullTo(linkedList<String>())
assertEquals(2, foo.size)
assertEquals(linkedList("foo", "bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSortedSet() {
val data = arrayList("foo", "bar")
val sorted = data.filterTo(sortedSet<String>()){it.length == 3}
assertEquals(2, sorted.size)
assertEquals(sortedSet("bar", "foo"), sorted)
assertTrue {
sorted is TreeSet<String>
}
}
//todo after KT-1873 the name might be returned to 'last'
test fun lastElement() {
val data = arrayList("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayList(15, 19, 20, 25).last())
assertEquals('a', linkedList('a').last())
}
test fun lastException() {
fails { linkedList<String>().last() }
}
test fun contains() {
assertTrue(linkedList(15, 19, 20).contains(15))
}
test fun sortBy() {
expect(arrayList("two" to 2, "three" to 3)) {
arrayList("three" to 3, "two" to 2).sortBy { it.second }
}
expect(arrayList("three" to 3, "two" to 2)) {
arrayList("three" to 3, "two" to 2).sortBy { it.first }
}
expect(arrayList("two" to 2, "three" to 3)) {
arrayList("three" to 3, "two" to 2).sortBy { it.first.length }
}
}
test fun sortFunctionShouldReturnSortedCopyForList() {
// TODO fixme Some sort of in/out variance thing - or an issue with Java interop?
todo {
// 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 : Iterable<Int> = arrayList(2, 3, 1)
// expect(arrayList(1, 2, 3)) { list.sort() }
// expect(arrayList(2, 3, 1)) { list }
}
}
}
-492
View File
@@ -1,492 +0,0 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionTest {
test fun all() {
val data = arrayList("foo", "bar")
assertTrue {
data.all{it.length == 3}
}
assertNot {
data.all{s -> s.startsWith("b")}
}
}
test fun any() {
val data = arrayList("foo", "bar")
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
test fun appendString() {
val data = arrayList("foo", "bar")
val buffer = StringBuilder()
val text = data.appendString(buffer, "-", "{", "}")
assertEquals("{foo-bar}", buffer.toString())
}
test fun count() {
val data = arrayList("foo", "bar")
assertEquals(1, data.count{it.startsWith("b")})
assertEquals(2, data.count{it.size == 3})
}
test fun filter() {
val data = arrayList("foo", "bar")
val foo = data.filter{it.startsWith("f")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(arrayList("foo"), foo)
}
test fun filterReturnsList() {
val data = arrayList("foo", "bar")
val foo = data.filter{it.startsWith("f")}
assertTrue {
foo is List<String>
}
}
test fun filterNot() {
val data = arrayList("foo", "bar")
val foo = data.filterNot{it.startsWith("b")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(arrayList("foo"), foo)
}
test fun filterNotNull() {
val data = arrayList(null, "foo", null, "bar")
val foo = data.filterNotNull()
assertEquals(2, foo.size)
assertEquals(arrayList("foo", "bar"), foo)
assertTrue {
foo is List<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSet() {
val data = arrayList("foo", "bar")
val foo = data.filterTo(hashSet<String>()){it.startsWith("f")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(hashSet("foo"), foo)
assertTrue {
foo is HashSet<String>
}
}
test fun find() {
val data = arrayList("foo", "bar")
val x = data.find{it.startsWith("x")}
assertNull(x)
val f = data.find{it.startsWith("f")}
f!!
assertEquals("foo", f)
}
test fun forEach() {
val data = arrayList("foo", "bar")
var count = 0
data.forEach{ count += it.length }
assertEquals(6, count)
}
test fun fold() {
// lets calculate the sum of some numbers
expect(10) {
val numbers = arrayList(1, 2, 3, 4)
numbers.fold(0){ a, b -> a + b}
}
expect(0) {
val numbers = arrayList<Int>()
numbers.fold(0){ a, b -> a + b}
}
// lets concatenate some strings
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.map{it.toString()}.fold(""){ a, b -> a + b}
}
}
test fun foldWithDifferentTypes() {
expect(7) {
val numbers = arrayList("a", "ab", "abc")
numbers.fold(1){ a, b -> a + b.size}
}
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.fold(""){ a, b -> a + b}
}
}
test fun foldWithNonCommutativeOperation() {
expect(1) {
val numbers = arrayList(1, 2, 3)
numbers.fold(7) {a, b -> a - b}
}
}
test fun foldRight() {
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.map{it.toString()}.foldRight(""){ a, b -> a + b}
}
}
test fun foldRightWithDifferentTypes() {
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.foldRight(""){ a, b -> "" + a + b}
}
}
test fun foldRightWithNonCommutativeOperation() {
expect(-5) {
val numbers = arrayList(1, 2, 3)
numbers.foldRight(7) {a, b -> a - b}
}
}
test fun partition() {
val data = arrayList("foo", "bar", "something", "xyz")
val pair = data.partition{it.size == 3}
assertEquals(arrayList("foo", "bar", "xyz"), pair.first, "pair.first")
assertEquals(arrayList("something"), pair.second, "pair.second")
}
test fun reduce() {
expect("1234") {
val list = arrayList("1", "2", "3", "4")
list.reduce { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayList<Int>().reduce { a, b -> a + b}
}
}
test fun reduceRight() {
expect("1234") {
val list = arrayList("1", "2", "3", "4")
list.reduceRight { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayList<Int>().reduceRight { a, b -> a + b}
}
}
test fun groupBy() {
val words = arrayList("a", "ab", "abc", "def", "abcd")
val byLength = words.groupBy{ it.length }
assertEquals(4, byLength.size())
val l3 = byLength.getOrElse(3, {ArrayList<String>()})
assertEquals(2, l3.size)
}
test fun makeString() {
val data = arrayList("foo", "bar")
val text = data.makeString("-", "<", ">")
assertEquals("<foo-bar>", text)
val big = arrayList("a", "b", "c", "d" , "e", "f")
val text2 = big.makeString(limit = 3, truncated = "*")
assertEquals("a, b, c, *", text2)
}
test fun map() {
val data = arrayList("foo", "bar")
val lengths = data.map{ it.length }
assertTrue {
lengths.all{it == 3}
}
assertEquals(2, lengths.size)
assertEquals(arrayList(3, 3), lengths)
}
test fun plus() {
val list = arrayList("foo", "bar")
val list2 = list + "cheese"
assertEquals(arrayList("foo", "bar"), list)
assertEquals(arrayList("foo", "bar", "cheese"), list2)
// lets use a mutable variable
var list3 = arrayList("a", "b")
list3 += "c"
assertEquals(arrayList("a", "b", "c"), list3)
}
test fun plusCollectionBug() {
val list = arrayList("foo", "bar") + arrayList("cheese", "wine")
assertEquals(arrayList("foo", "bar", "cheese", "wine"), list)
}
test fun plusCollection() {
val a = arrayList("foo", "bar")
val b = arrayList("cheese", "wine")
val list = a + b
assertEquals(arrayList("foo", "bar", "cheese", "wine"), list)
// lets use a mutable variable
var ml = a
ml += "beer"
ml += b
ml += "z"
assertEquals(arrayList("foo", "bar", "beer", "cheese", "wine", "z"), ml)
}
test fun requireNoNulls() {
val data = arrayList<String?>("foo", "bar")
val notNull = data.requireNoNulls()
assertEquals(arrayList("foo", "bar"), notNull)
val hasNulls = arrayList("foo", null, "bar")
failsWith(javaClass<IllegalArgumentException>()) {
// should throw an exception as we have a null
hasNulls.requireNoNulls()
}
}
test fun reverse() {
val data = arrayList("foo", "bar")
val rev = data.reverse()
assertEquals(arrayList("bar", "foo"), rev)
}
test fun reverseFunctionShouldReturnReversedCopyForList() {
val list : List<Int> = arrayList(2, 3, 1)
expect(arrayList(1, 3, 2)) { list.reverse() }
expect(arrayList(2, 3, 1)) { list }
}
test fun reverseFunctionShouldReturnReversedCopyForIterable() {
val iterable : Iterable<Int> = arrayList(2, 3, 1)
expect(arrayList(1, 3, 2)) { iterable.reverse() }
expect(arrayList(2, 3, 1)) { iterable }
}
test fun drop() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("bar", "abc"), coll.drop(1))
assertEquals(arrayList("abc"), coll.drop(2))
}
test fun dropWhile() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("bar", "abc"), coll.dropWhile{ it.startsWith("f") })
}
test fun take() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("foo"), coll.take(1))
assertEquals(arrayList("foo", "bar"), coll.take(2))
}
test fun takeWhile() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("foo"), coll.takeWhile{ it.startsWith("f") })
assertEquals(arrayList("foo", "bar", "abc"), coll.takeWhile{ it.size == 3 })
}
test fun toArray() {
val data = arrayList("foo", "bar")
val arr = data.toArray()
println("Got array ${arr}")
assertEquals(2, arr.size)
todo {
assertTrue {
arr is Array<String>
}
}
}
test fun simpleCount() {
val data = arrayList("foo", "bar")
assertEquals(2, data.count())
assertEquals(3, hashSet(12, 14, 15).count())
assertEquals(0, ArrayList<Double>().count())
}
//todo after KT-1873 the name might be returned to 'last'
test fun lastElement() {
val data = arrayList("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayList(15, 19, 20, 25).last())
assertEquals('a', arrayList('a').last())
}
// TODO
// assertEquals(19, TreeSet(arrayList(90, 47, 19)).first())
test fun lastException() {
fails { arrayList<Int>().last() }
}
test fun subscript() {
val list = arrayList("foo", "bar")
assertEquals("foo", list[0])
assertEquals("bar", list[1])
// lists throw an exception if out of range
fails {
assertEquals(null, list[2])
}
// lets try update the list
list[0] = "new"
list[1] = "thing"
// lists don't allow you to set past the end of the list
fails {
list[2] = "works"
}
list.add("works")
assertEquals(arrayList("new", "thing", "works"), list)
}
test fun indices() {
val data = arrayList("foo", "bar")
val indices = data.indices
assertEquals(0, indices.start)
assertEquals(1, indices.end)
assertEquals(indices, data.size. indices)
}
test fun contains() {
val data = arrayList("foo", "bar")
assertTrue(data.contains("foo"))
assertTrue(data.contains("bar"))
assertFalse(data.contains("some"))
// TODO: Problems with generation
// assertTrue(IterableWrapper(data).contains("bar"))
// assertFalse(IterableWrapper(data).contains("some"))
assertFalse(hashSet<Int>().contains(12))
assertTrue(arrayList(15, 19, 20).contains(15))
// assertTrue(IterableWrapper(hashSet(45, 14, 13)).contains(14))
// assertFalse(IterableWrapper(linkedList<Int>()).contains(15))
}
test fun sortForMutableIterable() {
val list : MutableIterable<Int> = arrayList<Int>(2, 3, 1)
expect(arrayList(1, 2, 3)) { list.sort() }
expect(arrayList(2, 3, 1)) { list }
}
test fun sortForIterable() {
val list : Iterable<Int> = listOf(2, 3, 1)
expect(arrayList(1, 2, 3)) { list.sort() }
expect(arrayList(2, 3, 1)) { list }
}
test fun min() {
expect(null, { listOf<Int>().min() })
expect(1, { listOf(1).min() })
expect(2, { listOf(2, 3).min() })
expect(2000000000000, { listOf(3000000000000, 2000000000000).min() })
expect('a', { listOf('a', 'b').min() })
expect("a", { listOf("a", "b").min() })
expect(null, { listOf<Int>().iterator().min() })
expect(2, { listOf(2, 3).iterator().min() })
}
test fun max() {
expect(null, { listOf<Int>().max() })
expect(1, { listOf(1).max() })
expect(3, { listOf(2, 3).max() })
expect(3000000000000, { listOf(3000000000000, 2000000000000).max() })
expect('b', { listOf('a', 'b').max() })
expect("b", { listOf("a", "b").max() })
expect(null, { listOf<Int>().iterator().max() })
expect(3, { listOf(2, 3).iterator().max() })
}
test fun minBy() {
expect(null, { listOf<Int>().minBy { it } })
expect(1, { listOf(1).minBy { it } })
expect(3, { listOf(2, 3).minBy { -it } })
expect('a', { listOf('a', 'b').minBy { "x$it" } })
expect("b", { listOf("b", "abc").minBy { it.length } })
expect(null, { listOf<Int>().iterator().minBy { it } })
expect(3, { listOf(2, 3).iterator().minBy { -it } })
}
test fun maxBy() {
expect(null, { listOf<Int>().maxBy { it } })
expect(1, { listOf(1).maxBy { it } })
expect(2, { listOf(2, 3).maxBy { -it } })
expect('b', { listOf('a', 'b').maxBy { "x$it" } })
expect("abc", { listOf("b", "abc").maxBy { it.length } })
expect(null, { listOf<Int>().iterator().maxBy { it } })
expect(2, { listOf(2, 3).iterator().maxBy { -it } })
}
test fun minByEvaluateOnce() {
var c = 0
expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(1, { listOf(5, 4, 3, 2, 1).iterator().minBy { c++; it * it } })
assertEquals(5, c)
}
test fun maxByEvaluateOnce() {
var c = 0
expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(5, { listOf(5, 4, 3, 2, 1).iterator().maxBy { c++; it * it } })
assertEquals(5, c)
}
test fun sum() {
expect(0) { ArrayList<Int>().sum() }
expect(14) { arrayListOf(2, 3, 9).sum() }
expect(3.0) { arrayListOf(1.0, 2.0).sum() }
expect(3000000000000) { arrayListOf<Long>(1000000000000, 2000000000000).sum() }
expect(3.0.toFloat()) { arrayListOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
}
class IterableWrapper<T>(collection : Iterable<T>) : Iterable<T> {
private val collection = collection
override fun iterator(): Iterator<T> {
return collection.iterator()
}
}
}
+4 -4
View File
@@ -42,8 +42,8 @@ class CompareTest {
val diff = c.compare(v1, v2)
assertTrue(diff < 0)
val items = arrayList(v1, v2)
items.sort(c)
val items = arrayListOf(v1, v2)
items.sortBy(c)
println("Sorted list in rating order $items")
}
@@ -60,8 +60,8 @@ class CompareTest {
val diff = c.compare(v1, v2)
assertTrue(diff > 0)
val items = arrayList(v1, v2)
items.sort(c)
val items = arrayListOf(v1, v2)
items.sortBy(c)
println("Sorted list in rating order $items")
}
@@ -1,18 +0,0 @@
import java.util.Vector
import junit.framework.TestCase
import kotlin.test.assertEquals
class EnumerationIteratorTest() : TestCase() {
fun testIteration () {
val v = Vector<Int>()
for(i in 1..5)
v.add(i)
var sum = 0
for(k in v.elements())
sum += k
assertEquals(15, sum)
}
}
-79
View File
@@ -1,79 +0,0 @@
package test.collections
import java.util.ArrayList
import kotlin.test.*
import org.junit.Test as test
class ListTest {
test fun _toString() {
val data = arrayList("foo", "bar")
assertEquals("[foo, bar]", data.toString())
}
test fun emptyHead() {
val data = ArrayList<String>()
assertNull(data.head)
}
test fun head() {
val data = arrayList("foo", "bar")
assertEquals("foo", data.head)
}
test fun tail() {
val data = arrayList("foo", "bar", "whatnot")
val actual = data.tail
val expected = arrayList("bar", "whatnot")
assertEquals(expected, actual)
}
test fun emptyFirst() {
val data = ArrayList<String>()
assertNull(data.first)
}
test fun first() {
val data = arrayList("foo", "bar")
assertEquals("foo", data.first)
}
test fun last() {
val data = arrayList("foo", "bar")
assertEquals("bar", data.last)
}
test fun forEachWithIndex() {
val data = arrayList("foo", "bar")
var index = 0
data.forEachWithIndex { (i, d) ->
assertEquals(i, index)
assertEquals(d, data[index])
index++
}
assertEquals(data.size(), index)
}
test fun withIndices() {
val data = arrayList("foo", "bar")
var index = 0
for ((i, d) in data.withIndices()) {
assertEquals(i, index)
assertEquals(d, data[index])
index++
}
assertEquals(data.size(), index)
}
test fun lastIndex() {
val emptyData = ArrayList<String>()
val data = arrayList("foo", "bar")
assertEquals(-1, emptyData.lastIndex)
assertEquals(1, data.lastIndex)
}
}
-65
View File
@@ -1,65 +0,0 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test
class SetTest {
val data = hashSet("foo", "bar")
Test fun any() {
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
Test fun all() {
assertTrue {
data.all{it.length == 3}
}
assertNot {
data.all{(s: String) -> s.startsWith("b")}
}
}
Test fun filter() {
val foo = data.filter{it.startsWith("f")}.toSet()
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(hashSet("foo"), foo)
assertTrue("Filter on a Set should return a Set") {
foo is Set<String>
}
}
Test fun find() {
val x = data.find{it.startsWith("x")}
assertNull(x)
val f = data.find{it.startsWith("f")}
assertEquals("foo", f)
}
Test fun map() {
/**
TODO compiler bug
we should be able to remove the explicit type on the function
http://youtrack.jetbrains.net/issue/KT-849
*/
val lengths = data.map{s -> s.length}
assertTrue {
lengths.all{it == 3}
}
assertEquals(2, lengths.size)
assertEquals(arrayList(3, 3), lengths)
}
}
@@ -1,22 +0,0 @@
package test.collections
import kotlin.*
import kotlin.test.*
import junit.framework.TestCase
class StandardCollectionTest() : TestCase() {
fun testDisabled() {
}
fun testAny() {
val data: Iterable<String> = listOf("foo", "bar")
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
}
@@ -1,4 +1,4 @@
package test.arrays
package test.collections
import kotlin.test.*
import org.junit.Test as test
@@ -1,4 +1,4 @@
package test.arrays
package test.collections
import kotlin.test.*
import org.junit.Test as test
@@ -153,8 +153,7 @@ class ArraysTest {
expect(3.0) { array(1.0, 2.0).sum() }
expect(200) { array<Byte>(100, 100).sum() }
expect(50000) { array<Short>(20000, 30000).sum() }
//TODO: uncomment when toLong() will be supported
//expect(3000000000000) { array<Long>(1000000000000, 2000000000000).sum() }
expect(3000000000000) { array<Long>(1000000000000, 2000000000000).sum() }
expect(3.0.toFloat()) { array<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
}
@@ -165,6 +164,28 @@ class ArraysTest {
expect(2) { array("cat", "dog", "bird").indexOf("bird") }
expect(0) { array(null, "dog", null).indexOf(null)}
}
test fun plus() {
assertEquals(listOf("1","2","3","4"), array("1", "2") + array("3", "4"))
assertEquals(listOf("1","2","3","4"), listOf("1", "2") + array("3", "4"))
}
test fun first() {
expect(1) { array(1,2,3).first() }
expect(2) { array(1,2,3).first { it % 2 == 0 } }
}
test fun last() {
expect(3) { array(1,2,3).last() }
expect(2) { array(1,2,3).last { it % 2 == 0 } }
}
test fun contains() {
assertTrue(array("1","2","3","4").contains("2"))
assertTrue("3" in array("1","2","3","4"))
assertTrue("0" !in array("1","2","3","4"))
}
/*
TODO FIXME ASAP: These currently fail on JS due to missing upto() method on numbers
@@ -0,0 +1,115 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionJVMTest {
test fun flatMap() {
val data = arrayListOf("", "foo", "bar", "x", "")
val characters = data.flatMap { it.toCharList() }
println("Got list of characters ${characters}")
assertEquals(7, characters.size())
val text = characters.makeString("")
assertEquals("foobarx", text)
}
test fun filterIntolinkedListOf() {
val data = arrayListOf("foo", "bar")
val foo = data.filterTo(linkedListOf<String>()) { it.startsWith("f") }
assertTrue {
foo.all { it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(linkedListOf("foo"), foo)
assertTrue {
foo is LinkedList<String>
}
}
test fun filterNotIntolinkedListOf() {
val data = arrayListOf("foo", "bar")
val foo = data.filterNotTo(linkedListOf<String>()) { it.startsWith("f") }
assertTrue {
foo.all { !it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(linkedListOf("bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterNotNullIntolinkedListOf() {
val data = arrayListOf(null, "foo", null, "bar")
val foo = data.filterNotNullTo(linkedListOf<String>())
assertEquals(2, foo.size)
assertEquals(linkedListOf("foo", "bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSortedSet() {
val data = arrayListOf("foo", "bar")
val sorted = data.filterTo(sortedSetOf<String>()) { it.length == 3 }
assertEquals(2, sorted.size)
assertEquals(sortedSetOf("bar", "foo"), sorted)
assertTrue {
sorted is TreeSet<String>
}
}
test fun last() {
val data = arrayListOf("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayListOf(15, 19, 20, 25).last())
assertEquals('a', linkedListOf('a').last())
}
test fun lastException() {
fails { linkedListOf<String>().last() }
}
test fun contains() {
assertTrue(linkedListOf(15, 19, 20).contains(15))
}
test fun sortBy() {
expect(arrayListOf("two" to 2, "three" to 3)) {
arrayListOf("three" to 3, "two" to 2).sortBy { it.second }
}
expect(arrayListOf("three" to 3, "two" to 2)) {
arrayListOf("three" to 3, "two" to 2).sortBy { it.first }
}
expect(arrayListOf("two" to 2, "three" to 3)) {
arrayListOf("three" to 3, "two" to 2).sortBy { it.first.length }
}
}
test fun sortFunctionShouldReturnSortedCopyForList() {
val list: List<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun sortFunctionShouldReturnSortedCopyForIterable() {
val list: Iterable<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
}
@@ -0,0 +1,432 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionTest {
test fun appendString() {
val data = arrayListOf("foo", "bar")
val buffer = StringBuilder()
val text = data.appendString(buffer, "-", "{", "}")
assertEquals("{foo-bar}", buffer.toString())
}
test fun makeString() {
val data = arrayListOf("foo", "bar")
val text = data.makeString("-", "<", ">")
assertEquals("<foo-bar>", text)
val big = arrayListOf("a", "b", "c", "d", "e", "f")
val text2 = big.makeString(limit = 3, truncated = "*")
assertEquals("a, b, c, *", text2)
}
test fun filterNotNull() {
val data = arrayListOf(null, "foo", null, "bar")
val foo = data.filterNotNull()
assertEquals(2, foo.size)
assertEquals(arrayListOf("foo", "bar"), foo)
assertTrue {
foo is List<String>
}
}
test fun mapNotNull() {
val data = arrayListOf(null, "foo", null, "bar")
val foo = data.mapNotNull { it.length }
assertEquals(2, foo.size)
assertEquals(arrayListOf(3, 3), foo)
assertTrue {
foo is List<Int>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSet() {
val data = arrayListOf("foo", "bar")
val foo = data.filterTo(hashSetOf<String>()) { it.startsWith("f") }
assertTrue {
foo.all { it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(hashSetOf("foo"), foo)
assertTrue {
foo is HashSet<String>
}
}
test fun fold() {
// lets calculate the sum of some numbers
expect(10) {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.fold(0) { a, b -> a + b }
}
expect(0) {
val numbers = arrayListOf<Int>()
numbers.fold(0) { a, b -> a + b }
}
// lets concatenate some strings
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.map { it.toString() }.fold("") { a, b -> a + b }
}
}
test fun foldWithDifferentTypes() {
expect(7) {
val numbers = arrayListOf("a", "ab", "abc")
numbers.fold(1) { a, b -> a + b.size }
}
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.fold("") { a, b -> a + b }
}
}
test fun foldWithNonCommutativeOperation() {
expect(1) {
val numbers = arrayListOf(1, 2, 3)
numbers.fold(7) { a, b -> a - b }
}
}
test fun foldRight() {
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.map { it.toString() }.foldRight("") { a, b -> a + b }
}
}
test fun foldRightWithDifferentTypes() {
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.foldRight("") { a, b -> "" + a + b }
}
}
test fun foldRightWithNonCommutativeOperation() {
expect(-5) {
val numbers = arrayListOf(1, 2, 3)
numbers.foldRight(7) { a, b -> a - b }
}
}
test fun partition() {
val data = arrayListOf("foo", "bar", "something", "xyz")
val pair = data.partition { it.size == 3 }
assertEquals(arrayListOf("foo", "bar", "xyz"), pair.first, "pair.first")
assertEquals(arrayListOf("something"), pair.second, "pair.second")
}
test fun reduce() {
expect("1234") {
val list = arrayListOf("1", "2", "3", "4")
list.reduce { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayListOf<Int>().reduce { a, b -> a + b }
}
}
test fun reduceRight() {
expect("1234") {
val list = arrayListOf("1", "2", "3", "4")
list.reduceRight { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayListOf<Int>().reduceRight { a, b -> a + b }
}
}
test fun groupBy() {
val words = arrayListOf("a", "ab", "abc", "def", "abcd")
val byLength = words.groupBy { it.length }
assertEquals(4, byLength.size())
val l3 = byLength.getOrElse(3, { ArrayList<String>() })
assertEquals(2, l3.size)
}
test fun plusRanges() {
val range1 = 1..3
val range2 = 4..7
val combined = range1 + range2
assertEquals((1..7).toList(), combined)
}
test fun mapRanges() {
val range = 1..3 map { it * 2}
assertEquals(listOf(2,4,6), range)
}
test fun plus() {
val list = arrayListOf("foo", "bar")
val list2 = list + "cheese"
assertEquals(arrayListOf("foo", "bar"), list)
assertEquals(arrayListOf("foo", "bar", "cheese"), list2)
// lets use a mutable variable
var list3 = arrayListOf("a", "b")
list3 += "c"
assertEquals(arrayListOf("a", "b", "c"), list3)
}
test fun plusCollectionBug() {
val list = arrayListOf("foo", "bar") + arrayListOf("cheese", "wine")
assertEquals(arrayListOf("foo", "bar", "cheese", "wine"), list)
}
test fun plusCollection() {
val a = arrayListOf("foo", "bar")
val b = arrayListOf("cheese", "wine")
val list = a + b
assertEquals(arrayListOf("foo", "bar", "cheese", "wine"), list)
// lets use a mutable variable
var ml = a
ml += "beer"
ml += b
ml += "z"
assertEquals(arrayListOf("foo", "bar", "beer", "cheese", "wine", "z"), ml)
}
test fun requireNoNulls() {
val data = arrayListOf<String?>("foo", "bar")
val notNull = data.requireNoNulls()
assertEquals(arrayListOf("foo", "bar"), notNull)
val hasNulls = arrayListOf("foo", null, "bar")
failsWith(javaClass<IllegalArgumentException>()) {
// should throw an exception as we have a null
hasNulls.requireNoNulls()
}
}
test fun reverse() {
val data = arrayListOf("foo", "bar")
val rev = data.reverse()
assertEquals(arrayListOf("bar", "foo"), rev)
}
test fun reverseFunctionShouldReturnReversedCopyForList() {
val list: List<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 3, 2)) { list.reverse() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun reverseFunctionShouldReturnReversedCopyForIterable() {
val iterable: Iterable<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 3, 2)) { iterable.reverse() }
expect(arrayListOf(2, 3, 1)) { iterable }
}
test fun drop() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("bar", "abc"), coll.drop(1))
assertEquals(arrayListOf("abc"), coll.drop(2))
}
test fun dropWhile() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("bar", "abc"), coll.dropWhile { it.startsWith("f") })
}
test fun take() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("foo"), coll.take(1))
assertEquals(arrayListOf("foo", "bar"), coll.take(2))
}
test fun takeWhile() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("foo"), coll.takeWhile { it.startsWith("f") })
assertEquals(arrayListOf("foo", "bar", "abc"), coll.takeWhile { it.size == 3 })
}
test fun toArray() {
val data = arrayListOf("foo", "bar")
val arr = data.toArray()
println("Got array ${arr}")
assertEquals(2, arr.size)
todo {
assertTrue {
arr is Array<String>
}
}
}
test fun simpleCount() {
val data = arrayListOf("foo", "bar")
assertEquals(2, data.count())
assertEquals(3, hashSetOf(12, 14, 15).count())
assertEquals(0, ArrayList<Double>().count())
}
//todo after KT-1873 the name might be returned to 'last'
test fun lastElement() {
val data = arrayListOf("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayListOf(15, 19, 20, 25).last())
assertEquals('a', arrayListOf('a').last())
}
// TODO
// assertEquals(19, TreeSet(arrayListOf(90, 47, 19)).first())
test fun lastException() {
fails { arrayListOf<Int>().last() }
}
test fun subscript() {
val list = arrayListOf("foo", "bar")
assertEquals("foo", list[0])
assertEquals("bar", list[1])
// lists throw an exception if out of range
fails {
assertEquals(null, list[2])
}
// lets try update the list
list[0] = "new"
list[1] = "thing"
// lists don't allow you to set past the end of the list
fails {
list[2] = "works"
}
list.add("works")
assertEquals(arrayListOf("new", "thing", "works"), list)
}
test fun indices() {
val data = arrayListOf("foo", "bar")
val indices = data.indices
assertEquals(0, indices.start)
assertEquals(1, indices.end)
assertEquals(indices, data.size. indices)
}
test fun contains() {
val data = arrayListOf("foo", "bar")
assertTrue(data.contains("foo"))
assertTrue(data.contains("bar"))
assertFalse(data.contains("some"))
// TODO: Problems with generation
// assertTrue(IterableWrapper(data).contains("bar"))
// assertFalse(IterableWrapper(data).contains("some"))
assertFalse(hashSetOf<Int>().contains(12))
assertTrue(arrayListOf(15, 19, 20).contains(15))
// assertTrue(IterableWrapper(hashSet(45, 14, 13)).contains(14))
// assertFalse(IterableWrapper(linkedList<Int>()).contains(15))
}
test fun sortForMutableIterable() {
val list: MutableIterable<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun sortForIterable() {
val list: Iterable<Int> = listOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun min() {
expect(null, { listOf<Int>().min() })
expect(1, { listOf(1).min() })
expect(2, { listOf(2, 3).min() })
expect(2000000000000, { listOf(3000000000000, 2000000000000).min() })
expect('a', { listOf('a', 'b').min() })
expect("a", { listOf("a", "b").min() })
expect(null, { listOf<Int>().stream().min() })
expect(2, { listOf(2, 3).stream().min() })
}
test fun max() {
expect(null, { listOf<Int>().max() })
expect(1, { listOf(1).max() })
expect(3, { listOf(2, 3).max() })
expect(3000000000000, { listOf(3000000000000, 2000000000000).max() })
expect('b', { listOf('a', 'b').max() })
expect("b", { listOf("a", "b").max() })
expect(null, { listOf<Int>().stream().max() })
expect(3, { listOf(2, 3).stream().max() })
}
test fun minBy() {
expect(null, { listOf<Int>().minBy { it } })
expect(1, { listOf(1).minBy { it } })
expect(3, { listOf(2, 3).minBy { -it } })
expect('a', { listOf('a', 'b').minBy { "x$it" } })
expect("b", { listOf("b", "abc").minBy { it.length } })
expect(null, { listOf<Int>().stream().minBy { it } })
expect(3, { listOf(2, 3).stream().minBy { -it } })
}
test fun maxBy() {
expect(null, { listOf<Int>().maxBy { it } })
expect(1, { listOf(1).maxBy { it } })
expect(2, { listOf(2, 3).maxBy { -it } })
expect('b', { listOf('a', 'b').maxBy { "x$it" } })
expect("abc", { listOf("b", "abc").maxBy { it.length } })
expect(null, { listOf<Int>().stream().maxBy { it } })
expect(2, { listOf(2, 3).stream().maxBy { -it } })
}
test fun minByEvaluateOnce() {
var c = 0
expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(1, { listOf(5, 4, 3, 2, 1).stream().minBy { c++; it * it } })
assertEquals(5, c)
}
test fun maxByEvaluateOnce() {
var c = 0
expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(5, { listOf(5, 4, 3, 2, 1).stream().maxBy { c++; it * it } })
assertEquals(5, c)
}
test fun sum() {
expect(0) { arrayListOf<Int>().sum() }
expect(14) { arrayListOf(2, 3, 9).sum() }
expect(3.0) { arrayListOf(1.0, 2.0).sum() }
expect(3000000000000) { arrayListOf<Long>(1000000000000, 2000000000000).sum() }
expect(3.0.toFloat()) { arrayListOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
}
class IterableWrapper<T>(collection: Iterable<T>) : Iterable<T> {
private val collection = collection
override fun iterator(): Iterator<T> {
return collection.iterator()
}
}
}
@@ -1,4 +1,4 @@
package test.collection
package test.collections
import kotlin.test.*
@@ -0,0 +1,9 @@
package test.collections
import org.junit.Test
import kotlin.test.*
import java.util.*
class LinkedSetTest : OrderedIterableTests<Set<String>>(setOf("foo", "bar"), setOf<String>())
class LinkedListTest : OrderedIterableTests<LinkedList<String>>(linkedListOf("foo", "bar"), linkedListOf<String>())
@@ -0,0 +1,203 @@
package test.collections
import org.junit.Test
import kotlin.test.*
import java.util.*
class SetTest : IterableTests<Set<String>>(hashSetOf("foo", "bar"), hashSetOf<String>())
class ListTest : OrderedIterableTests<List<String>>(listOf("foo", "bar"), listOf<String>())
class ArrayListTest : OrderedIterableTests<ArrayList<String>>(arrayListOf("foo", "bar"), arrayListOf<String>())
abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : IterableTests<T>(data, empty) {
Test fun indexOf() {
expect(0) { data.indexOf("foo") }
expect(-1) { empty.indexOf("foo") }
expect(1) { data.indexOf("bar") }
expect(-1) { data.indexOf("zap") }
}
Test fun lastIndexOf() {
expect(0) { data.lastIndexOf("foo") }
expect(-1) { empty.lastIndexOf("foo") }
expect(1) { data.lastIndexOf("bar") }
expect(-1) { data.lastIndexOf("zap") }
}
Test fun elementAt() {
expect("foo") { data.elementAt(0) }
expect("bar") { data.elementAt(1) }
fails { data.elementAt(2) }
fails { data.elementAt(-1) }
fails { empty.elementAt(0) }
}
Test fun first() {
expect("foo") { data.first() }
fails {
data.first { it.startsWith("x") }
}
fails {
empty.first()
}
expect("foo") { data.first { it.startsWith("f") } }
}
Test fun firstOrNull() {
expect(null) { data.firstOrNull { it.startsWith("x") } }
expect(null) { empty.firstOrNull() }
val f = data.firstOrNull { it.startsWith("f") }
assertEquals("foo", f)
}
Test fun last() {
assertEquals("bar", data.last())
fails {
data.last { it.startsWith("x") }
}
fails {
empty.last()
}
expect("foo") { data.last { it.startsWith("f") } }
}
Test fun lastOrNull() {
expect(null) { data.lastOrNull { it.startsWith("x") } }
expect(null) { empty.lastOrNull() }
expect("foo") { data.lastOrNull { it.startsWith("f") } }
}
}
abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
Test fun any() {
expect(true) { data.any() }
expect(false) { empty.any() }
expect(true) { data.any { it.startsWith("f") } }
expect(false) { data.any { it.startsWith("x") } }
expect(false) { empty.any { it.startsWith("x") } }
}
Test fun all() {
expect(true) { data.all { it.length == 3 } }
expect(false) { data.all { it.startsWith("b") } }
expect(true) { empty.all { it.startsWith("b") } }
}
Test fun none() {
expect(false) { data.none() }
expect(true) { empty.none() }
expect(false) { data.none { it.length == 3 } }
expect(false) { data.none { it.startsWith("b") } }
expect(true) { data.none { it.startsWith("x") } }
expect(true) { empty.none { it.startsWith("b") } }
}
Test fun filter() {
val foo = data.filter { it.startsWith("f") }
// TODO uncomment this when KT-4651 will be fixed
//expect(true) { foo is List<String> }
expect(true) { foo.all { it.startsWith("f") } }
expect(1) { foo.size }
assertEquals(listOf("foo"), foo)
}
Test fun filterNot() {
val notFoo = data.filterNot { it.startsWith("f") }
// TODO uncomment this when KT-4651 will be fixed
//expect(true) { notFoo is List<String> }
expect(true) { notFoo.none { it.startsWith("f") } }
expect(1) { notFoo.size }
assertEquals(listOf("bar"), notFoo)
}
Test fun forEach() {
var count = 0
data.forEach { count += it.length }
assertEquals(6, count)
}
Test fun contains() {
assertTrue(data.contains("foo"))
assertTrue("bar" in data)
assertTrue("baz" !in data)
assertFalse("baz" in empty)
}
Test fun single() {
fails { data.single() }
fails { empty.single() }
expect("foo") { data.single { it.startsWith("f") } }
expect("bar") { data.single { it.startsWith("b") } }
fails {
data.single { it.length == 3 }
}
}
Test
fun singleOrNull() {
fails { data.singleOrNull() }
fails { empty.singleOrNull() }
expect("foo") { data.singleOrNull { it.startsWith("f") } }
expect("bar") { data.singleOrNull { it.startsWith("b") } }
fails {
data.singleOrNull { it.length == 3 }
}
}
Test
fun map() {
val lengths = data.map { it.length }
assertTrue {
lengths.all { it == 3 }
}
assertEquals(2, lengths.size)
assertEquals(arrayListOf(3, 3), lengths)
}
Test
fun max() {
expect("foo") { data.max() }
expect("bar") { data.maxBy { it.last() } }
}
Test
fun min() {
expect("bar") { data.min() }
expect("foo") { data.minBy { it.last() } }
}
Test
fun count() {
expect(2) { data.count() }
expect(0) { empty.count() }
expect(1) { data.count { it.startsWith("f") } }
expect(0) { empty.count { it.startsWith("f") } }
expect(0) { data.count { it.startsWith("x") } }
expect(0) { empty.count { it.startsWith("x") } }
}
Test
fun withIndices() {
var index = 0
for ((i, d) in data.withIndices()) {
assertEquals(i, index)
assertEquals(d, data.elementAt(index))
index++
}
assertEquals(data.count(), index)
}
Test
fun fold() {
}
Test
fun reduce() {
}
}
@@ -0,0 +1,44 @@
package test.collections
import org.junit.Test as test
import kotlin.test.*
import java.util.*
class IteratorsJVMTest {
test fun testEnumeration() {
val v = Vector<Int>()
for(i in 1..5)
v.add(i)
var sum = 0
for(k in v.elements())
sum += k
assertEquals(15, sum)
}
test fun flatMapAndTakeExtractTheTransformedElements() {
fun intToBinaryDigits() = { (i: Int) ->
val binary = Integer.toBinaryString(i)!!
var index = 0
stream<Char> { if (index < binary.length()) binary.get(index++) else null }
}
val expected = arrayListOf(
'0', // fibonacci(0) = 0
'1', // fibonacci(1) = 1
'1', // fibonacci(2) = 1
'1', '0', // fibonacci(3) = 2
'1', '1', // fibonacci(4) = 3
'1', '0', '1' // fibonacci(5) = 5
)
assertEquals(expected, fibonacci().flatMap<Int, Char>(intToBinaryDigits()).take(10).toList())
}
test fun flatMapOnStream() {
val result = listOf(1, 2).stream().flatMap<Int, Int> { (0..it).stream() }
assertEquals(listOf(0, 1, 0, 1, 2), result.toList())
}
}
@@ -0,0 +1,15 @@
package test.collections
import kotlin.test.*
import org.junit.Test as test
class IteratorsTest {
test fun iterationOverIterator() {
val c = arrayListOf(0, 1, 2, 3, 4, 5)
var s = ""
for (i in c.iterator()) {
s = s + i.toString()
}
assertEquals("012345", s)
}
}
@@ -0,0 +1,33 @@
package test.collections
import java.util.ArrayList
import kotlin.test.*
import org.junit.Test
class ListSpecificTest {
val data = listOf("foo", "bar")
val empty = listOf<String>()
Test fun _toString() {
assertEquals("[foo, bar]", data.toString())
}
Test fun tail() {
val data = arrayListOf("foo", "bar", "whatnot")
val actual = data.tail
val expected = arrayListOf("bar", "whatnot")
assertEquals(expected, actual)
}
Test fun utils() {
assertNull(empty.head)
assertNull(empty.first)
assertNull(empty.last)
assertEquals(-1, empty.lastIndex)
assertEquals("foo", data.head)
assertEquals("foo", data.first)
assertEquals("bar", data.last)
assertEquals(1, data.lastIndex)
}
}
@@ -17,11 +17,11 @@ class MutableCollectionTest {
assertEquals(data, collection)
}
test fun fromIterator() {
test fun fromStream() {
val list = arrayListOf("foo", "bar")
val collection = ArrayList<String>()
collection.addAll(list.iterator())
collection.addAll(list.stream())
assertEquals(list, collection)
}
@@ -0,0 +1,148 @@
package test.collections
import org.junit.Test
import kotlin.test.*
import java.util.*
fun fibonacci(): Stream<Int> {
// fibonacci terms
var index = 0;
var a = 0;
var b = 1
return stream<Int> {
when (index++) { 0 -> a; 1 -> b; else -> {
val result = a + b; a = b; b = result; result
} }
}
}
public class StreamTest {
Test fun requireNoNulls() {
val stream = arrayListOf<String?>("foo", "bar").stream()
val notNull = stream.requireNoNulls()
assertEquals(arrayListOf("foo", "bar"), notNull.toList())
val streamWithNulls = arrayListOf("foo", null, "bar").stream()
val notNull2 = streamWithNulls.requireNoNulls() // shouldn't fail yet
fails {
// should throw an exception as we have a null
notNull2.toList()
}
}
test fun mapNotNull() {
val data = arrayListOf(null, "foo", null, "bar").stream()
val foo = data.mapNotNull { it.length }
assertEquals(arrayListOf(3, 3), foo.toList())
assertTrue {
foo is Stream<Int>
}
}
Test fun filterAndTakeWhileExtractTheElementsWithinRange() {
assertEquals(arrayListOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList())
}
Test fun foldReducesTheFirstNElements() {
val sum = {(a: Int, b: Int) -> a + b }
assertEquals(arrayListOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum))
}
Test fun takeExtractsTheFirstNElements() {
assertEquals(arrayListOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList())
}
Test fun mapAndTakeWhileExtractTheTransformedElements() {
assertEquals(arrayListOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile {(i: Int) -> i < 20 }.toList())
}
Test fun joinConcatenatesTheFirstNElementsAboveAThreshold() {
assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.makeString(separator = ", ", limit = 5))
}
Test fun skippingIterator() {
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).makeString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(3).drop(4).makeString(limit = 10))
}
Test fun toStringJoinsNoMoreThanTheFirstTenElements() {
assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().makeString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.makeString(limit = 10))
assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.makeString())
}
Test fun plus() {
val stream = listOf("foo", "bar").stream()
val streamChease = stream + "cheese"
assertEquals(listOf("foo", "bar", "cheese"), streamChease.toList())
// lets use a mutable variable
var mi = listOf("a", "b").stream()
mi += "c"
assertEquals(listOf("a", "b", "c"), mi.toList())
}
Test fun plusCollection() {
val a = listOf("foo", "bar")
val b = listOf("cheese", "wine")
val stream = a.stream() + b
assertEquals(listOf("foo", "bar", "cheese", "wine"), stream.toList())
// lets use a mutable variable
var ml = listOf("a").stream()
ml += a
ml += "beer"
ml += b
ml += "z"
assertEquals(listOf("a", "foo", "bar", "beer", "cheese", "wine", "z"), ml.toList())
}
Test fun iterationOverStream() {
val c = arrayListOf(0, 1, 2, 3, 4, 5)
var s = ""
for (i in c.stream()) {
s = s + i.toString()
}
assertEquals("012345", s)
}
Test fun streamFromFunction() {
var count = 3
val stream = stream<Int> {
count--
if (count >= 0) count else null
}
val list = stream.toList()
assertEquals(listOf(2, 1, 0), list)
}
Test fun streamFromFunctionWithInitialValue() {
val values = stream<Int>(3) { n -> if (n > 0) n - 1 else null }
assertEquals(arrayListOf(3, 2, 1, 0), values.toList())
}
private fun <T, C : MutableCollection<in T>> Stream<T>.takeWhileTo(result: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
Test fun streamExtensions() {
val c = arrayListOf(0, 1, 2, 3, 4, 5)
val d = ArrayList<Int>()
c.stream().takeWhileTo(d, { i -> i < 4 })
assertEquals(4, d.size())
}
/*
Test fun pairIterator() {
val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).makeString(limit = 10)
assertEquals("(0, 0), (1, 2), (1, 2), (2, 4), (3, 6), (5, 10), (8, 16), (13, 26), (21, 42), (34, 68), ...", pairStr)
}
*/
}
@@ -1,4 +1,4 @@
package serial
package test.concurrent
import java.io.ObjectOutputStream
import java.io.ByteArrayOutputStream
@@ -1,4 +1,4 @@
package concurrent
package test.concurrent
import kotlin.concurrent.*
import kotlin.test.*
@@ -1,4 +1,4 @@
package concurrent
package test.concurrent
import kotlin.concurrent.*
import kotlin.test.*
+1 -1
View File
@@ -39,7 +39,7 @@ class NextSiblingTest {
val elems = doc["#id3"]
val element = elems.first()
val elements = element.nextElements().toList()
val elements = element.nextElements()
val nodes = element.nextSiblings().toList()
assertEquals(1, elements.size())
@@ -1,4 +1,4 @@
package test.collections
package test.io
import kotlin.test.*
@@ -12,7 +12,7 @@ class IoTest(){
test fun testLineIteratorWithManualClose() {
val reader = sample().buffered()
try {
val list = reader.lineIterator().toArrayList()
val list = reader.lines().toArrayList()
assertEquals(arrayListOf("Hello", "World"), list)
} finally {
reader.close()
+2 -2
View File
@@ -175,14 +175,14 @@ class MapJsTest {
*/
test fun createUsingPairs() {
val map = hashMap(Pair("a", 1), Pair("b", 2))
val map = mapOf(Pair("a", 1), Pair("b", 2))
assertEquals(2, map.size)
assertEquals(1, map.get("a"))
assertEquals(2, map.get("b"))
}
test fun createUsingTo() {
val map = hashMap("a" to 1, "b" to 2)
val map = mapOf("a" to 1, "b" to 2)
assertEquals(2, map.size)
assertEquals(1, map.get("a"))
assertEquals(2, map.get("b"))
+17 -17
View File
@@ -6,7 +6,7 @@ import org.junit.Test
class SetJsTest {
val data: Set<String> = createTestMutableSet()
val empty: Set<String> = hashSet<String>()
val empty: Set<String> = hashSetOf<String>()
Test fun size() {
assertEquals(2, data.size())
@@ -39,10 +39,10 @@ class SetJsTest {
}
Test fun containsAll() {
assertTrue(data.containsAll(arrayList("foo", "bar")))
assertTrue(data.containsAll(arrayList<String>()))
assertFalse(data.containsAll(arrayList("foo", "bar", "baz")))
assertFalse(data.containsAll(arrayList("baz")))
assertTrue(data.containsAll(arrayListOf("foo", "bar")))
assertTrue(data.containsAll(arrayListOf<String>()))
assertFalse(data.containsAll(arrayListOf("foo", "bar", "baz")))
assertFalse(data.containsAll(arrayListOf("baz")))
}
Test fun add() {
@@ -51,7 +51,7 @@ class SetJsTest {
assertEquals(3, data.size())
assertFalse(data.add("baz"))
assertEquals(3, data.size())
assertTrue(data.containsAll(arrayList("foo", "bar", "baz")))
assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz")))
}
Test fun remove() {
@@ -65,36 +65,36 @@ class SetJsTest {
Test fun addAll() {
val data = createTestMutableSet()
assertTrue(data.addAll(arrayList("foo", "bar", "baz", "boo")))
assertTrue(data.addAll(arrayListOf("foo", "bar", "baz", "boo")))
assertEquals(4, data.size())
assertFalse(data.addAll(arrayList("foo", "bar", "baz", "boo")))
assertFalse(data.addAll(arrayListOf("foo", "bar", "baz", "boo")))
assertEquals(4, data.size())
assertTrue(data.containsAll(arrayList("foo", "bar", "baz", "boo")))
assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz", "boo")))
}
Test fun removeAll() {
val data = createTestMutableSet()
assertFalse(data.removeAll(arrayList("baz")))
assertTrue(data.containsAll(arrayList("foo", "bar")))
assertFalse(data.removeAll(arrayListOf("baz")))
assertTrue(data.containsAll(arrayListOf("foo", "bar")))
assertEquals(2, data.size())
assertTrue(data.removeAll(arrayList("foo")))
assertTrue(data.removeAll(arrayListOf("foo")))
assertTrue(data.contains("bar"))
assertEquals(1, data.size())
assertTrue(data.removeAll(arrayList("foo", "bar")))
assertTrue(data.removeAll(arrayListOf("foo", "bar")))
assertEquals(0, data.size())
val data2 = createTestMutableSet()
assertFalse(data.removeAll(arrayList("foo", "bar", "baz")))
assertFalse(data.removeAll(arrayListOf("foo", "bar", "baz")))
assertTrue(data.isEmpty())
}
Test fun retainAll() {
val data1 = createTestMutableSet()
assertTrue(data1.retainAll(arrayList("baz")))
assertTrue(data1.retainAll(arrayListOf("baz")))
assertTrue(data1.isEmpty())
val data2 = createTestMutableSet()
assertTrue(data2.retainAll(arrayList("foo")))
assertTrue(data2.retainAll(arrayListOf("foo")))
assertTrue(data2.contains("foo"))
assertEquals(1, data2.size())
}
@@ -109,5 +109,5 @@ class SetJsTest {
}
//Helpers
fun createTestMutableSet(): MutableSet<String> = hashSet("foo", "bar")
fun createTestMutableSet(): MutableSet<String> = hashSetOf("foo", "bar")
}
@@ -1,4 +1,4 @@
package test.string
package test.text
import kotlin.test.*
@@ -252,7 +252,9 @@ class StringJVMTest {
test fun drop() {
val data = "abcd1234"
assertEquals("d1234", data.drop(3))
assertEquals(data, data.drop(-2))
fails {
data.drop(-2)
}
assertEquals("", data.drop(data.length + 5))
}
@@ -265,7 +267,9 @@ class StringJVMTest {
test fun take() {
val data = "abcd1234"
assertEquals("abc", data.take(3))
assertEquals("", data.take(-7))
fails {
data.take(-7)
}
assertEquals(data, data.take(data.length + 42))
}
@@ -1,4 +1,4 @@
package test
package test.text
import kotlin.test.*
import org.junit.Test as test
@@ -1,4 +1,4 @@
package test.string
package test.text
import kotlin.*
import kotlin.test.*