Added 'public' annotation and specified return types for library functions

This commit is contained in:
Svetlana Isakova
2012-03-29 20:45:59 +04:00
parent aefabd132e
commit 167a9c444a
55 changed files with 1435 additions and 1435 deletions
@@ -15,12 +15,12 @@ import java.util.*
*
* @includeFunction ../../test/CollectionTest.kt map
*/
inline fun <T, R> Array<T>.map(transform : (T) -> R) : java.util.List<R> {
public inline fun <T, R> Array<T>.map(transform : (T) -> R) : java.util.List<R> {
return mapTo(java.util.ArrayList<R>(this.size), transform)
}
/** Transforms each element of this collection with the given function then adds the results to the given collection */
inline fun <T, R, C: Collection<in R>> Array<T>.mapTo(result: C, transform : (T) -> R) : C {
public inline fun <T, R, C: Collection<in R>> Array<T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
return result
@@ -15,12 +15,12 @@ import java.util.*
*
* @includeFunction ../../test/CollectionTest.kt map
*/
inline fun <T, R> java.lang.Iterable<T>.map(transform : (T) -> R) : java.util.List<R> {
public inline fun <T, R> java.lang.Iterable<T>.map(transform : (T) -> R) : java.util.List<R> {
return mapTo(java.util.ArrayList<R>(), transform)
}
/** Transforms each element of this collection with the given function then adds the results to the given collection */
inline fun <T, R, C: Collection<in R>> java.lang.Iterable<T>.mapTo(result: C, transform : (T) -> R) : C {
public inline fun <T, R, C: Collection<in R>> java.lang.Iterable<T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
return result
@@ -15,12 +15,12 @@ import java.util.*
*
* @includeFunction ../../test/CollectionTest.kt map
*/
inline fun <T, R> Iterable<T>.map(transform : (T) -> R) : java.util.List<R> {
public inline fun <T, R> Iterable<T>.map(transform : (T) -> R) : java.util.List<R> {
return mapTo(java.util.ArrayList<R>(), transform)
}
/** Transforms each element of this collection with the given function then adds the results to the given collection */
inline fun <T, R, C: Collection<in R>> Iterable<T>.mapTo(result: C, transform : (T) -> R) : C {
public inline fun <T, R, C: Collection<in R>> Iterable<T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
return result
+74 -74
View File
@@ -8,103 +8,103 @@ import java.util.List
import java.util.ArrayList
// Array "constructor"
inline fun <T> array(vararg t : T) : Array<T> = t
public inline fun <T> array(vararg t : T) : Array<T> = t
// "constructors" for primitive types array
inline fun doubleArray(vararg content : Double) = content
public inline fun doubleArray(vararg content : Double) : DoubleArray = content
inline fun floatArray(vararg content : Float) = content
public inline fun floatArray(vararg content : Float) : FloatArray = content
inline fun longArray(vararg content : Long) = content
public inline fun longArray(vararg content : Long) : LongArray = content
inline fun intArray(vararg content : Int) = content
public inline fun intArray(vararg content : Int) : IntArray = content
inline fun charArray(vararg content : Char) = content
public inline fun charArray(vararg content : Char) : CharArray = content
inline fun shortArray(vararg content : Short) = content
public inline fun shortArray(vararg content : Short) : ShortArray = content
inline fun byteArray(vararg content : Byte) = content
public inline fun byteArray(vararg content : Byte) : ByteArray = content
inline fun booleanArray(vararg content : Boolean) = content
public inline fun booleanArray(vararg content : Boolean) : BooleanArray = content
inline fun ByteArray.binarySearch(key: Byte) = Arrays.binarySearch(this, key)
inline fun ShortArray.binarySearch(key: Short) = Arrays.binarySearch(this, key)
inline fun IntArray.binarySearch(key: Int) = Arrays.binarySearch(this, key)
inline fun LongArray.binarySearch(key: Long) = Arrays.binarySearch(this, key)
inline fun FloatArray.binarySearch(key: Float) = Arrays.binarySearch(this, key)
inline fun DoubleArray.binarySearch(key: Double) = Arrays.binarySearch(this, key)
inline fun CharArray.binarySearch(key: Char) = Arrays.binarySearch(this, key)
public inline fun ByteArray.binarySearch(key: Byte) : Int = Arrays.binarySearch(this, key)
public inline fun ShortArray.binarySearch(key: Short) : Int = Arrays.binarySearch(this, key)
public inline fun IntArray.binarySearch(key: Int) : Int = Arrays.binarySearch(this, key)
public inline fun LongArray.binarySearch(key: Long) : Int = Arrays.binarySearch(this, key)
public inline fun FloatArray.binarySearch(key: Float) : Int = Arrays.binarySearch(this, key)
public inline fun DoubleArray.binarySearch(key: Double) : Int = Arrays.binarySearch(this, key)
public inline fun CharArray.binarySearch(key: Char) : Int = Arrays.binarySearch(this, key)
inline fun ByteArray.binarySearch(fromIndex: Int, toIndex: Int, key: Byte) = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun ShortArray.binarySearch(fromIndex: Int, toIndex: Int, key: Short) = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun IntArray.binarySearch(fromIndex: Int, toIndex: Int, key: Int) = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun LongArray.binarySearch(fromIndex: Int, toIndex: Int, key: Long) = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun FloatArray.binarySearch(fromIndex: Int, toIndex: Int, key: Float) = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun DoubleArray.binarySearch(fromIndex: Int, toIndex: Int, key: Double) = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun CharArray.binarySearch(fromIndex: Int, toIndex: Int, key: Char) = Arrays.binarySearch(this, fromIndex, toIndex, key)
public inline fun ByteArray.binarySearch(fromIndex: Int, toIndex: Int, key: Byte) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public inline fun ShortArray.binarySearch(fromIndex: Int, toIndex: Int, key: Short) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public inline fun IntArray.binarySearch(fromIndex: Int, toIndex: Int, key: Int) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public inline fun LongArray.binarySearch(fromIndex: Int, toIndex: Int, key: Long) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public inline fun FloatArray.binarySearch(fromIndex: Int, toIndex: Int, key: Float) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public inline fun DoubleArray.binarySearch(fromIndex: Int, toIndex: Int, key: Double) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
public inline fun CharArray.binarySearch(fromIndex: Int, toIndex: Int, key: Char) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
/*
inline fun <T> Array<T>.binarySearch(key: T, comparator: fun(T,T):Int) = Arrays.binarySearch(this, key, object: java.util.Comparator<T> {
override fun compare(a: T, b: T) = comparator(a, b)
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)
override fun equals(obj: Any?) = obj.identityEquals(this)
public override fun equals(obj: Any?) = obj.identityEquals(this)
})
*/
inline fun BooleanArray.fill(value: Boolean) = Arrays.fill(this, value)
inline fun ByteArray.fill(value: Byte) = Arrays.fill(this, value)
inline fun ShortArray.fill(value: Short) = Arrays.fill(this, value)
inline fun IntArray.fill(value: Int) = Arrays.fill(this, value)
inline fun LongArray.fill(value: Long) = Arrays.fill(this, value)
inline fun FloatArray.fill(value: Float) = Arrays.fill(this, value)
inline fun DoubleArray.fill(value: Double) = Arrays.fill(this, value)
inline fun CharArray.fill(value: Char) = Arrays.fill(this, value)
public inline fun BooleanArray.fill(value: Boolean) : Unit = Arrays.fill(this, value)
public inline fun ByteArray.fill(value: Byte) : Unit = Arrays.fill(this, value)
public inline fun ShortArray.fill(value: Short) : Unit = Arrays.fill(this, value)
public inline fun IntArray.fill(value: Int) : Unit = Arrays.fill(this, value)
public inline fun LongArray.fill(value: Long) : Unit = Arrays.fill(this, value)
public inline fun FloatArray.fill(value: Float) : Unit = Arrays.fill(this, value)
public inline fun DoubleArray.fill(value: Double) : Unit = Arrays.fill(this, value)
public inline fun CharArray.fill(value: Char) : Unit = Arrays.fill(this, value)
inline fun <in T: Any?> Array<T>.fill(value: T) = Arrays.fill(this as Array<Any?>, value)
public inline fun <in T: Any?> Array<T>.fill(value: T) : Unit = Arrays.fill(this as Array<Any?>, value)
inline fun ByteArray.sort() = Arrays.sort(this)
inline fun ShortArray.sort() = Arrays.sort(this)
inline fun IntArray.sort() = Arrays.sort(this)
inline fun LongArray.sort() = Arrays.sort(this)
inline fun FloatArray.sort() = Arrays.sort(this)
inline fun DoubleArray.sort() = Arrays.sort(this)
inline fun CharArray.sort() = Arrays.sort(this)
public inline fun ByteArray.sort() : Unit = Arrays.sort(this)
public inline fun ShortArray.sort() : Unit = Arrays.sort(this)
public inline fun IntArray.sort() : Unit = Arrays.sort(this)
public inline fun LongArray.sort() : Unit = Arrays.sort(this)
public inline fun FloatArray.sort() : Unit = Arrays.sort(this)
public inline fun DoubleArray.sort() : Unit = Arrays.sort(this)
public inline fun CharArray.sort() : Unit = Arrays.sort(this)
inline fun ByteArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex)
inline fun ShortArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex)
inline fun IntArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex)
inline fun LongArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex)
inline fun FloatArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex)
inline fun DoubleArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex)
inline fun CharArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex)
public inline fun ByteArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public inline fun ShortArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public inline fun IntArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public inline fun LongArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public inline fun FloatArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public inline fun DoubleArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
public inline fun CharArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
inline fun BooleanArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
inline fun ByteArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
inline fun ShortArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
inline fun IntArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
inline fun LongArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
inline fun FloatArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
inline fun DoubleArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
inline fun CharArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure()
public inline fun BooleanArray.copyOf(newLength: Int = this.size) : BooleanArray = Arrays.copyOf(this, newLength).sure()
public inline fun ByteArray.copyOf(newLength: Int = this.size) : ByteArray = Arrays.copyOf(this, newLength).sure()
public inline fun ShortArray.copyOf(newLength: Int = this.size) : ShortArray = Arrays.copyOf(this, newLength).sure()
public inline fun IntArray.copyOf(newLength: Int = this.size) : IntArray = Arrays.copyOf(this, newLength).sure()
public inline fun LongArray.copyOf(newLength: Int = this.size) : LongArray = Arrays.copyOf(this, newLength).sure()
public inline fun FloatArray.copyOf(newLength: Int = this.size) : FloatArray = Arrays.copyOf(this, newLength).sure()
public inline fun DoubleArray.copyOf(newLength: Int = this.size) : DoubleArray = Arrays.copyOf(this, newLength).sure()
public inline fun CharArray.copyOf(newLength: Int = this.size) : CharArray = Arrays.copyOf(this, newLength).sure()
inline fun <T> Array<T>.copyOf(newLength: Int = this.size) : Array<T> = Arrays.copyOf(this as Array<T?>, newLength) as Array<T>
public inline fun <T> Array<T>.copyOf(newLength: Int = this.size) : Array<T> = Arrays.copyOf(this as Array<T?>, newLength) as Array<T>
inline fun BooleanArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
inline fun ByteArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
inline fun ShortArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
inline fun IntArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
inline fun LongArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
inline fun FloatArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
inline fun DoubleArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
inline fun CharArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure()
public inline fun BooleanArray.copyOfRange(from: Int, to: Int) : BooleanArray = Arrays.copyOfRange(this, from, to).sure()
public inline fun ByteArray.copyOfRange(from: Int, to: Int) : ByteArray = Arrays.copyOfRange(this, from, to).sure()
public inline fun ShortArray.copyOfRange(from: Int, to: Int) : ShortArray = Arrays.copyOfRange(this, from, to).sure()
public inline fun IntArray.copyOfRange(from: Int, to: Int) : IntArray = Arrays.copyOfRange(this, from, to).sure()
public inline fun LongArray.copyOfRange(from: Int, to: Int) : LongArray = Arrays.copyOfRange(this, from, to).sure()
public inline fun FloatArray.copyOfRange(from: Int, to: Int) : FloatArray = Arrays.copyOfRange(this, from, to).sure()
public inline fun DoubleArray.copyOfRange(from: Int, to: Int) : DoubleArray = Arrays.copyOfRange(this, from, to).sure()
public inline fun CharArray.copyOfRange(from: Int, to: Int) : CharArray = Arrays.copyOfRange(this, from, to).sure()
inline fun <T> Array<T>.copyOfRange(from: Int, to: Int) : Array<T> = Arrays.copyOfRange(this as Array<T?>, from, to) as Array<T>
public inline fun <T> Array<T>.copyOfRange(from: Int, to: Int) : Array<T> = Arrays.copyOfRange(this as Array<T?>, from, to) as Array<T>
inline val ByteArray.inputStream : ByteArrayInputStream
get() = ByteArrayInputStream(this)
inline fun ByteArray.inputStream(offset: Int, length: Int) = ByteArrayInputStream(this, offset, length)
public inline fun ByteArray.inputStream(offset: Int, length: Int) : ByteArrayInputStream = ByteArrayInputStream(this, offset, length)
inline fun ByteArray.toString(encoding: String?): String {
public inline fun ByteArray.toString(encoding: String?): String {
if (encoding != null) {
return String(this, encoding)
} else {
@@ -112,18 +112,18 @@ inline fun ByteArray.toString(encoding: String?): String {
}
}
inline fun ByteArray.toString(encoding: Charset) = String(this, encoding)
public inline fun ByteArray.toString(encoding: Charset) : String = String(this, encoding)
/** Returns true if the array is not empty */
inline fun <T> Array<T>.notEmpty() : Boolean = !this.isEmpty()
public inline fun <T> Array<T>.notEmpty() : Boolean = !this.isEmpty()
/** Returns true if the array is empty */
inline fun <T> Array<T>.isEmpty() : Boolean = this.size == 0
public inline fun <T> Array<T>.isEmpty() : Boolean = this.size == 0
/** Returns the array if its not null or else returns an empty array */
inline fun <T> Array<T>?.orEmpty() : Array<T> = if (this != null) this else array<T>()
public inline fun <T> Array<T>?.orEmpty() : Array<T> = if (this != null) this else array<T>()
inline fun CharArray.toList(): List<Character> {
public inline fun CharArray.toList(): List<Character> {
val list = ArrayList<Character>(this.size)
for (c in this) {
if (c != null) {
+1 -1
View File
@@ -1,6 +1,6 @@
package kotlin
inline fun Int.times(body : () -> Unit) {
public inline fun Int.times(body : () -> Unit) {
var count = this;
while (count > 0) {
body()
+1 -1
View File
@@ -5,7 +5,7 @@ import java.lang.Object
import jet.runtime.Intrinsic
val <out T> T.javaClass : Class<T>
public val <out T> T.javaClass : Class<T>
[Intrinsic("kotlin.javaClass.property")] get() = (this as java.lang.Object).getClass() as Class<T>
[Intrinsic("kotlin.javaClass.function")] fun <out T> javaClass() : Class<T> = null as Class<T>
+21 -21
View File
@@ -11,18 +11,18 @@ import java.util.Collections
/** Returns the size of the map */
val JMap<*,*>.size : Int
get() = size()
get() = size()
/** Returns true if this map is empty */
val JMap<*,*>.empty : Boolean
get() = isEmpty()
get() = isEmpty()
/** Provides [] access to maps */
fun <K, V> JMap<K, V>.set(key : K, value : V) = this.put(key, value)
public fun <K, V> JMap<K, V>.set(key : K, value : V) : V? = this.put(key, value)
/** Returns the [[Map]] if its not null otherwise it returns the empty [[Map]] */
inline fun <K,V> java.util.Map<K,V>?.orEmpty() : java.util.Map<K,V>
= if (this != null) this else Collections.EMPTY_MAP as java.util.Map<K,V>
public inline fun <K,V> java.util.Map<K,V>?.orEmpty() : java.util.Map<K,V>
= if (this != null) this else Collections.EMPTY_MAP as java.util.Map<K,V>
/** Returns the key of the entry */
@@ -40,13 +40,13 @@ inline fun <K,V> java.util.Map<K,V>?.orEmpty() : java.util.Map<K,V>
*
* @includeFunction ../../test/MapTest.kt getOrElse
*/
inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V {
val current = this.get(key)
if (current != null) {
return current
} else {
return defaultValue()
}
public inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V {
val current = this.get(key)
if (current != null) {
return current
} else {
return defaultValue()
}
}
/**
@@ -54,13 +54,13 @@ inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V
*
* @includeFunction ../../test/MapTest.kt getOrElse
*/
inline fun <K,V> java.util.Map<K,V>.getOrPut(key: K, defaultValue: ()-> V) : V {
val current = this.get(key)
if (current != null) {
return current
} else {
val answer = defaultValue()
this.put(key, answer)
return answer
}
public inline fun <K,V> java.util.Map<K,V>.getOrPut(key: K, defaultValue: ()-> V) : V {
val current = this.get(key)
if (current != null) {
return current
} else {
val answer = defaultValue()
this.put(key, answer)
return answer
}
}
+17 -17
View File
@@ -12,26 +12,26 @@ val Collection<*>.empty : Boolean
get() = isEmpty()
/** Returns a new ArrayList with a variable number of initial elements */
inline fun arrayList<T>(vararg values: T) : ArrayList<T> = values.to(ArrayList<T>(values.size))
public inline fun arrayList<T>(vararg values: T) : ArrayList<T> = values.to(ArrayList<T>(values.size))
/** Returns a new LinkedList with a variable number of initial elements */
inline fun linkedList<T>(vararg values: T) : LinkedList<T> = values.to(LinkedList<T>())
public inline fun linkedList<T>(vararg values: T) : LinkedList<T> = values.to(LinkedList<T>())
/** Returns a new HashSet with a variable number of initial elements */
inline fun hashSet<T>(vararg values: T) : HashSet<T> = values.to(HashSet<T>(values.size))
public inline fun hashSet<T>(vararg values: T) : HashSet<T> = values.to(HashSet<T>(values.size))
/** Returns a new SortedSet with a variable number of initial elements */
inline fun sortedSet<T>(vararg values: T) : TreeSet<T> = values.to(TreeSet<T>())
public inline fun sortedSet<T>(vararg values: T) : TreeSet<T> = values.to(TreeSet<T>())
inline fun <K,V> hashMap(): HashMap<K,V> = HashMap<K,V>()
public inline fun <K,V> hashMap(): HashMap<K,V> = HashMap<K,V>()
inline fun <K,V> sortedMap(): SortedMap<K,V> = TreeMap<K,V>()
public inline fun <K,V> sortedMap(): SortedMap<K,V> = TreeMap<K,V>()
val Collection<*>.indices : IntRange
get() = 0..size-1
inline fun <T> java.util.Collection<T>.toArray() : Array<T> {
public inline fun <T> java.util.Collection<T>.toArray() : Array<T> {
val answer = Array<T>(this.size)
var idx = 0
for (elem in this)
@@ -40,37 +40,37 @@ inline fun <T> java.util.Collection<T>.toArray() : Array<T> {
}
/** TODO these functions don't work when they generate the Array<T> versions when they are in JavaIterables */
inline fun <in T: java.lang.Comparable<T>> java.lang.Iterable<T>.toSortedList() : List<T> = toList().sort()
public inline fun <in T: java.lang.Comparable<T>> java.lang.Iterable<T>.toSortedList() : List<T> = toList().sort()
inline fun <in T: java.lang.Comparable<T>> java.lang.Iterable<T>.toSortedList(comparator: java.util.Comparator<T>) : List<T> = toList().sort(comparator)
public inline fun <in T: java.lang.Comparable<T>> java.lang.Iterable<T>.toSortedList(comparator: java.util.Comparator<T>) : List<T> = toList().sort(comparator)
// List APIs
inline fun <in T: java.lang.Comparable<T>> List<T>.sort() : List<T> {
public inline fun <in T: java.lang.Comparable<T>> List<T>.sort() : List<T> {
Collections.sort(this)
return this
}
inline fun <in T> List<T>.sort(comparator: java.util.Comparator<T>) : List<T> {
public inline fun <in T> List<T>.sort(comparator: java.util.Comparator<T>) : List<T> {
Collections.sort(this, comparator)
return this
}
/** Returns the List if its not null otherwise returns the empty list */
inline fun <T> java.util.List<T>?.orEmpty() : java.util.List<T>
public inline fun <T> java.util.List<T>?.orEmpty() : java.util.List<T>
= if (this != null) this else Collections.EMPTY_LIST as java.util.List<T>
/** Returns the Set if its not null otherwise returns the empty set */
inline fun <T> java.util.Set<T>?.orEmpty() : java.util.Set<T>
public inline fun <T> java.util.Set<T>?.orEmpty() : java.util.Set<T>
= if (this != null) this else Collections.EMPTY_SET as java.util.Set<T>
/**
TODO figure out necessary variance/generics ninja stuff... :)
inline fun <in T> List<T>.sort(transform: fun(T) : java.lang.Comparable<*>) : List<T> {
public inline fun <in T> List<T>.sort(transform: fun(T) : java.lang.Comparable<*>) : List<T> {
val comparator = java.util.Comparator<T>() {
fun compare(o1: T, o2: T): Int {
public fun compare(o1: T, o2: T): Int {
val v1 = transform(o1)
val v2 = transform(o2)
if (v1 == v2) {
@@ -101,9 +101,9 @@ val <T> List<T>.last : T?
/** Returns true if the collection is not empty */
inline fun <T> java.util.Collection<T>.notEmpty() : Boolean = !this.isEmpty()
public inline fun <T> java.util.Collection<T>.notEmpty() : Boolean = !this.isEmpty()
/** Returns the Collection if its not null otherwise it returns the empty list */
inline fun <T> java.util.Collection<T>?.orEmpty() : Collection<T>
public inline fun <T> java.util.Collection<T>?.orEmpty() : Collection<T>
= if (this != null) this else Collections.EMPTY_LIST as Collection<T>
@@ -14,12 +14,12 @@ import java.util.*
*
* @includeFunction ../../test/CollectionTest.kt map
*/
inline fun <T, R> java.util.Collection<T>.map(transform : (T) -> R) : java.util.List<R> {
public inline fun <T, R> java.util.Collection<T>.map(transform : (T) -> R) : java.util.List<R> {
return mapTo(java.util.ArrayList<R>(this.size), transform)
}
/** Transforms each element of this collection with the given function then adds the results to the given collection */
inline fun <T, R, C: Collection<in R>> java.util.Collection<T>.mapTo(result: C, transform : (T) -> R) : C {
public inline fun <T, R, C: Collection<in R>> java.util.Collection<T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
return result
@@ -12,7 +12,7 @@ import java.util.Iterator
* If base collection implements [[Collection]] interface method [[Collection.size()]] will be used.
* Otherwise, this method determines the count by iterating through the all items.
*/
fun <T> java.lang.Iterable<T>.count() : Int {
public fun <T> java.lang.Iterable<T>.count() : Int {
if (this is Collection<T>) {
return this.size()
}
@@ -30,7 +30,7 @@ fun <T> java.lang.Iterable<T>.count() : Int {
* Will throw an exception if there are no elements
*/
// TODO: Specify type of the exception
inline fun <T> java.lang.Iterable<T>.first() : T {
public inline fun <T> java.lang.Iterable<T>.first() : T {
if (this is AbstractList<T>) {
return this.get(0)
}
@@ -50,7 +50,7 @@ inline fun <T> java.lang.Iterable<T>.first() : T {
* @includeFunction ../../test/CollectionTest.kt last
*/
// TODO: Specify type of the exception
fun <T> java.lang.Iterable<T>.last() : T {
public fun <T> java.lang.Iterable<T>.last() : T {
if (this is List<T>) {
return this.get(this.size() - 1);
}
@@ -72,7 +72,7 @@ fun <T> java.lang.Iterable<T>.last() : T {
* If collection implements [[java.util.AbstractCollection]] an overridden implementation of the contains
* method will be used.
*/
fun <T> java.lang.Iterable<T>.contains(item : T) : Boolean {
public fun <T> java.lang.Iterable<T>.contains(item : T) : Boolean {
if (this is java.util.AbstractCollection<T>) {
return this.contains(item);
}
@@ -89,9 +89,9 @@ fun <T> java.lang.Iterable<T>.contains(item : T) : Boolean {
/**
* Convert collection of arbitrary elements to collection of tuples of the index and the element
*/
fun <T> java.lang.Iterable<T>.withIndices() : java.lang.Iterable<#(Int, T)> {
public fun <T> java.lang.Iterable<T>.withIndices() : java.lang.Iterable<#(Int, T)> {
return object : java.lang.Iterable<#(Int, T)> {
override fun iterator(): java.util.Iterator<#(Int, T)> {
public override fun iterator(): java.util.Iterator<#(Int, T)> {
// TODO explicit typecast as a workaround for KT-1457, should be removed when it is fixed
return NumberedIterator<T>(this@withIndices.iterator().sure()) as java.util.Iterator<#(Int, T)>
}
@@ -101,7 +101,7 @@ fun <T> java.lang.Iterable<T>.withIndices() : java.lang.Iterable<#(Int, T)> {
private class NumberedIterator<TT>(private val sourceIterator : java.util.Iterator<TT>) : java.util.Iterator<#(Int, TT)> {
private var nextIndex = 0
override fun remove() {
public override fun remove() {
try {
sourceIterator.remove()
nextIndex--;
@@ -110,11 +110,11 @@ private class NumberedIterator<TT>(private val sourceIterator : java.util.Iterat
}
}
override fun hasNext(): Boolean {
public override fun hasNext(): Boolean {
return sourceIterator.hasNext();
}
override fun next(): #(Int, TT) {
public override fun next(): #(Int, TT) {
val result = #(nextIndex, sourceIterator.next())
nextIndex++
return result
+6 -6
View File
@@ -25,7 +25,7 @@ inline fun <T> compareBy(a: T?, b: T?, vararg functions: Function1<T, Any?>): In
* they are compared via [[#equals()]] and if they are not the same then
* the [[#hashCode()]] method is used as the difference
*/
inline fun <T> compareValues(a: T?, b: T?): Int {
public inline fun <T> compareValues(a: T?, b: T?): Int {
if (a == null) return - 1
if (b == null) return 1
if (a is Comparable<T>) {
@@ -44,23 +44,23 @@ inline fun <T> compareValues(a: T?, b: T?): Int {
}
/**
* Creates a comparator using the sequence of functions used to calcualte a value to compare on
* Creates a comparator using the sequence of functions used to calculate a value to compare on
*/
inline fun <T> comparator(vararg functions: Function1<T,Any?>): Comparator<T> {
public inline fun <T> comparator(vararg functions: Function1<T,Any?>): Comparator<T> {
return FunctionComparator<T>(functions)
}
private class FunctionComparator<T>(val functions: Array<Function1<T,Any?>>): Comparator<T> {
fun toString(): String {
public fun toString(): String {
return "FunctionComparator${functions.toList()}"
}
override fun compare(o1: T?, o2: T?): Int {
public override fun compare(o1: T?, o2: T?): Int {
return compareBy<T>(o1, o2, *functions)
}
override fun equals(obj: Any?): Boolean {
public override fun equals(obj: Any?): Boolean {
return this == obj
}
}
+9 -9
View File
@@ -9,7 +9,7 @@ object Assertions {
* Throws an [[AssertionError]] if the `value` is false and runtime assertions have been
* enabled on the JVM using the `-ea` JVM option.
*/
inline fun assert(value: Boolean): Unit {
public inline fun assert(value: Boolean): Unit {
if(Assertions._ENABLED) {
if(!value) {
throw AssertionError();
@@ -21,7 +21,7 @@ inline fun assert(value: Boolean): Unit {
* Throws an [[AssertionError]] with specified `message` if the `value` is false
* and runtime assertions have been enabled on the JVM using the `-ea` JVM option.
*/
inline fun assert(value: Boolean, message: Any) {
public inline fun assert(value: Boolean, message: Any) {
if(Assertions._ENABLED) {
if(!value) {
throw AssertionError(message);
@@ -33,7 +33,7 @@ inline fun assert(value: Boolean, message: Any) {
* Throws an [[AssertionError]] with specified `message` if the `value` is false
* and runtime assertions have been enabled on the JVM using the `-ea` JVM option.
*/
inline fun assert(value: Boolean, lazyMessage: () -> String) {
public inline fun assert(value: Boolean, lazyMessage: () -> String) {
if(Assertions._ENABLED) {
if(!value) {
val message = lazyMessage()
@@ -45,7 +45,7 @@ inline fun assert(value: Boolean, lazyMessage: () -> String) {
/**
* Throws an [[IllegalArgumentException]] if the `value` is false.
*/
inline fun require(value: Boolean): Unit {
public inline fun require(value: Boolean): Unit {
if(!value) {
throw IllegalArgumentException();
}
@@ -54,7 +54,7 @@ inline fun require(value: Boolean): Unit {
/**
* Throws an [[IllegalArgumentException]] with specified `message` if the `value` is false.
*/
inline fun require(value: Boolean, message: Any): Unit {
public inline fun require(value: Boolean, message: Any): Unit {
if(!value) {
throw IllegalArgumentException(message.toString());
}
@@ -63,7 +63,7 @@ inline fun require(value: Boolean, message: Any): Unit {
/**
* Throws an [[IllegalArgumentException]] with specified `message` if the `value` is false.
*/
inline fun require(value: Boolean, lazyMessage: () -> String): Unit {
public inline fun require(value: Boolean, lazyMessage: () -> String): Unit {
if(!value) {
val message = lazyMessage()
throw IllegalArgumentException(message.toString());
@@ -73,7 +73,7 @@ inline fun require(value: Boolean, lazyMessage: () -> String): Unit {
/**
* Throws an [[IllegalStateException]] if the `value` is false.
*/
inline fun check(value: Boolean): Unit {
public inline fun check(value: Boolean): Unit {
if(!value) {
throw IllegalStateException();
}
@@ -82,7 +82,7 @@ inline fun check(value: Boolean): Unit {
/**
* Throws an [[IllegalStateException]] with specified `message` if the `value` is false.
*/
inline fun check(value: Boolean, message: Any): Unit {
public inline fun check(value: Boolean, message: Any): Unit {
if(!value) {
throw IllegalStateException(message.toString());
}
@@ -93,7 +93,7 @@ inline fun check(value: Boolean, message: Any): Unit {
/**
* Throws an [[IllegalStateException]] with specified `message` if the `value` is false.
*/
inline fun check(value: Boolean, lazyMessage: () -> String): Unit {
public inline fun check(value: Boolean, lazyMessage: () -> String): Unit {
if(!value) {
val message = lazyMessage()
throw IllegalStateException(message.toString());
+12 -12
View File
@@ -10,21 +10,21 @@ import java.util.TreeSet
/**
Helper to make jet.Iterator usable in for
*/
inline fun <T> Iterator<T>.iterator() = this
public inline fun <T> Iterator<T>.iterator() : Iterator<T> = this
/**
Helper to make java.util.Iterator usable in for
*/
inline fun <T> java.util.Iterator<T>.iterator() = this
public inline fun <T> java.util.Iterator<T>.iterator() : java.util.Iterator<T> = this
/**
Helper to make java.util.Enumeration usable in for
*/
fun <erased T> java.util.Enumeration<T>.iterator(): Iterator<T> = object: Iterator<T> {
override val hasNext: Boolean
public fun <erased T> java.util.Enumeration<T>.iterator(): Iterator<T> = object: Iterator<T> {
override val hasNext: Boolean
get() = hasMoreElements()
override fun next() = nextElement().sure()
public override fun next() : T = nextElement().sure()
}
/*
@@ -34,7 +34,7 @@ fun <erased T> java.util.Enumeration<T>.iterator(): Iterator<T> = object: Iterat
/**
Add iterated elements to given container
*/
fun <T,U: Collection<in T>> Iterator<T>.to(container: U) : U {
public fun <T,U: Collection<in T>> Iterator<T>.to(container: U) : U {
while(hasNext)
container.add(next())
return container
@@ -43,29 +43,29 @@ fun <T,U: Collection<in T>> Iterator<T>.to(container: U) : U {
/**
Add iterated elements to java.util.ArrayList
*/
inline fun <T> Iterator<T>.toArrayList() = to(ArrayList<T>())
public inline fun <T> Iterator<T>.toArrayList() : ArrayList<T> = to(ArrayList<T>())
/**
Add iterated elements to java.util.LinkedList
*/
inline fun <T> Iterator<T>.toLinkedList() = to(LinkedList<T>())
public inline fun <T> Iterator<T>.toLinkedList() : LinkedList<T> = to(LinkedList<T>())
/**
Add iterated elements to java.util.HashSet
*/
inline fun <T> Iterator<T>.toHashSet() = to(HashSet<T>())
public inline fun <T> Iterator<T>.toHashSet() : HashSet<T> = to(HashSet<T>())
/**
Add iterated elements to java.util.LinkedHashSet
*/
inline fun <T> Iterator<T>.toLinkedHashSet() = to(LinkedHashSet<T>())
public inline fun <T> Iterator<T>.toLinkedHashSet() : LinkedHashSet<T> = to(LinkedHashSet<T>())
/**
Add iterated elements to java.util.TreeSet
*/
inline fun <T> Iterator<T>.toTreeSet() = to(TreeSet<T>())
public inline fun <T> Iterator<T>.toTreeSet() : TreeSet<T> = to(TreeSet<T>())
/**
Run function f
*/
inline fun <T> run(f: () -> T) = f()
public inline fun <T> run(f: () -> T) : T = f()
+84 -84
View File
@@ -4,30 +4,30 @@ import java.io.StringReader
import java.util.List
import java.util.ArrayList
inline fun String.lastIndexOf(str: String) = (this as java.lang.String).lastIndexOf(str)
public inline fun String.lastIndexOf(str: String) : Int = (this as java.lang.String).lastIndexOf(str)
inline fun String.lastIndexOf(ch: Char) = (this as java.lang.String).lastIndexOf(ch.toString())
public inline fun String.lastIndexOf(ch: Char) : Int = (this as java.lang.String).lastIndexOf(ch.toString())
inline fun String.equalsIgnoreCase(anotherString: String) = (this as java.lang.String).equalsIgnoreCase(anotherString)
public inline fun String.equalsIgnoreCase(anotherString: String) : Boolean = (this as java.lang.String).equalsIgnoreCase(anotherString)
inline fun String.indexOf(str : String) = (this as java.lang.String).indexOf(str)
public inline fun String.indexOf(str : String) : Int = (this as java.lang.String).indexOf(str)
inline fun String.indexOf(str : String, fromIndex : Int) = (this as java.lang.String).indexOf(str, fromIndex)
public inline fun String.indexOf(str : String, fromIndex : Int) : Int = (this as java.lang.String).indexOf(str, fromIndex)
inline fun String.replace(oldChar: Char, newChar : Char) = (this as java.lang.String).replace(oldChar, newChar).sure()
public inline fun String.replace(oldChar: Char, newChar : Char) : String = (this as java.lang.String).replace(oldChar, newChar).sure()
inline fun String.replaceAll(regex: String, replacement : String) = (this as java.lang.String).replaceAll(regex, replacement).sure()
public inline fun String.replaceAll(regex: String, replacement : String) : String = (this as java.lang.String).replaceAll(regex, replacement).sure()
inline fun String.trim() = (this as java.lang.String).trim().sure()
public inline fun String.trim() : String = (this as java.lang.String).trim().sure()
/** Returns the string with leading and trailing text matching the given string removed */
inline fun String.trim(text: String) = trimLeading(text).trimTrailing(text)
public inline fun String.trim(text: String) : String = trimLeading(text).trimTrailing(text)
/** Returns the string with the prefix and postfix text trimmed */
inline fun String.trim(prefix: String, postfix: String) = trimLeading(prefix).trimTrailing(postfix)
public inline fun String.trim(prefix: String, postfix: String) : String = trimLeading(prefix).trimTrailing(postfix)
/** Returns the string with the leading prefix of this string removed */
inline fun String.trimLeading(prefix: String): String {
public inline fun String.trimLeading(prefix: String): String {
var answer = this
if (answer.startsWith(prefix)) {
answer = answer.substring(prefix.length())
@@ -36,7 +36,7 @@ inline fun String.trimLeading(prefix: String): String {
}
/** Returns the string with the trailing postfix of this string removed */
inline fun String.trimTrailing(postfix: String): String {
public inline fun String.trimTrailing(postfix: String): String {
var answer = this
if (answer.endsWith(postfix)) {
answer = answer.substring(0, length() - postfix.length())
@@ -44,33 +44,33 @@ inline fun String.trimTrailing(postfix: String): String {
return answer
}
inline fun String.toUpperCase() = (this as java.lang.String).toUpperCase().sure()
public inline fun String.toUpperCase() : String = (this as java.lang.String).toUpperCase().sure()
inline fun String.toLowerCase() = (this as java.lang.String).toLowerCase().sure()
public inline fun String.toLowerCase() : String = (this as java.lang.String).toLowerCase().sure()
inline fun String.length() = (this as java.lang.String).length()
public inline fun String.length() : Int = (this as java.lang.String).length()
inline fun String.getBytes() = (this as java.lang.String).getBytes().sure()
public inline fun String.getBytes() : ByteArray = (this as java.lang.String).getBytes().sure()
inline fun String.toCharArray() = (this as java.lang.String).toCharArray().sure()
public inline fun String.toCharArray() : CharArray = (this as java.lang.String).toCharArray().sure()
inline fun String.toCharList(): List<Character> = toCharArray().toList()
public inline fun String.toCharList(): List<Character> = toCharArray().toList()
inline fun String.format(format : String, vararg args : Any?) = java.lang.String.format(format, args).sure()
public inline fun String.format(format : String, vararg args : Any?) : String = java.lang.String.format(format, args).sure()
inline fun String.split(regex : String) = (this as java.lang.String).split(regex)
public inline fun String.split(regex : String) : Array<String?>? = (this as java.lang.String).split(regex)
inline fun String.substring(beginIndex : Int) = (this as java.lang.String).substring(beginIndex).sure()
public inline fun String.substring(beginIndex : Int) : String = (this as java.lang.String).substring(beginIndex).sure()
inline fun String.substring(beginIndex : Int, endIndex : Int) = (this as java.lang.String).substring(beginIndex, endIndex).sure()
public inline fun String.substring(beginIndex : Int, endIndex : Int) : String = (this as java.lang.String).substring(beginIndex, endIndex).sure()
inline fun String.startsWith(prefix: String) = (this as java.lang.String).startsWith(prefix)
public inline fun String.startsWith(prefix: String) : Boolean = (this as java.lang.String).startsWith(prefix)
inline fun String.startsWith(prefix: String, toffset: Int) = (this as java.lang.String).startsWith(prefix, toffset)
public inline fun String.startsWith(prefix: String, toffset: Int) : Boolean = (this as java.lang.String).startsWith(prefix, toffset)
inline fun String.contains(seq: CharSequence) : Boolean = (this as java.lang.String).contains(seq)
public inline fun String.contains(seq: CharSequence) : Boolean = (this as java.lang.String).contains(seq)
inline fun String.endsWith(suffix: String) : Boolean = (this as java.lang.String).endsWith(suffix)
public inline fun String.endsWith(suffix: String) : Boolean = (this as java.lang.String).endsWith(suffix)
inline val String.size : Int
get() = length()
@@ -80,135 +80,135 @@ get() = StringReader(this)
// "constructors" for String
inline fun String(bytes : ByteArray, offset : Int, length : Int, charsetName : String) = java.lang.String(bytes, offset, length, charsetName) as String
public inline fun String(bytes : ByteArray, offset : Int, length : Int, charsetName : String) : String = java.lang.String(bytes, offset, length, charsetName) as String
inline fun String(bytes : ByteArray, offset : Int, length : Int, charset : java.nio.charset.Charset) = java.lang.String(bytes, offset, length, charset) as String
public inline fun String(bytes : ByteArray, offset : Int, length : Int, charset : java.nio.charset.Charset) : String = java.lang.String(bytes, offset, length, charset) as String
inline fun String(bytes : ByteArray, charsetName : String?) = java.lang.String(bytes, charsetName) as String
public inline fun String(bytes : ByteArray, charsetName : String?) : String = java.lang.String(bytes, charsetName) as String
inline fun String(bytes : ByteArray, charset : java.nio.charset.Charset) = java.lang.String(bytes, charset) as String
public inline fun String(bytes : ByteArray, charset : java.nio.charset.Charset) : String = java.lang.String(bytes, charset) as String
inline fun String(bytes : ByteArray, i : Int, i1 : Int) = java.lang.String(bytes, i, i1) as String
public inline fun String(bytes : ByteArray, i : Int, i1 : Int) : String = java.lang.String(bytes, i, i1) as String
inline fun String(bytes : ByteArray) = java.lang.String(bytes) as String
public inline fun String(bytes : ByteArray) : String = java.lang.String(bytes) as String
inline fun String(chars : CharArray) = java.lang.String(chars) as String
public inline fun String(chars : CharArray) : String = java.lang.String(chars) as String
inline fun String(stringBuffer : java.lang.StringBuffer) = java.lang.String(stringBuffer) as String
public inline fun String(stringBuffer : java.lang.StringBuffer) : String = java.lang.String(stringBuffer) as String
inline fun String(stringBuilder : java.lang.StringBuilder) = java.lang.String(stringBuilder) as String
public inline fun String(stringBuilder : java.lang.StringBuilder) : String = java.lang.String(stringBuilder) as String
/** Returns true if the string is not null and not empty */
inline fun String?.notEmpty() : Boolean = this != null && this.length() > 0
public inline fun String?.notEmpty() : Boolean = this != null && this.length() > 0
inline fun String.toByteArray(encoding: String?=null):ByteArray {
public inline fun String.toByteArray(encoding: String?=null):ByteArray {
if(encoding==null) {
return (this as java.lang.String).getBytes().sure()
} else {
return (this as java.lang.String).getBytes(encoding).sure()
}
}
inline fun String.toByteArray(encoding: java.nio.charset.Charset):ByteArray = (this as java.lang.String).getBytes(encoding).sure()
public inline fun String.toByteArray(encoding: java.nio.charset.Charset):ByteArray = (this as java.lang.String).getBytes(encoding).sure()
inline fun String.toBoolean() = java.lang.Boolean.parseBoolean(this).sure()
inline fun String.toShort() = java.lang.Short.parseShort(this).sure()
inline fun String.toInt() = java.lang.Integer.parseInt(this).sure()
inline fun String.toLong() = java.lang.Long.parseLong(this).sure()
inline fun String.toFloat() = java.lang.Float.parseFloat(this).sure()
inline fun String.toDouble() = java.lang.Double.parseDouble(this).sure()
public inline fun String.toBoolean() : Boolean = java.lang.Boolean.parseBoolean(this).sure()
public inline fun String.toShort() : Short = java.lang.Short.parseShort(this).sure()
public inline fun String.toInt() : Int = java.lang.Integer.parseInt(this).sure()
public inline fun String.toLong() : Long = java.lang.Long.parseLong(this).sure()
public inline fun String.toFloat() : Float = java.lang.Float.parseFloat(this).sure()
public inline fun String.toDouble() : Double = java.lang.Double.parseDouble(this).sure()
/**
* Converts the string into a regular expression [[Pattern]] optionally
* with the specified flags from [[Pattern]] or'd together
* so that strings can be split or matched on.
*/
inline fun String.toRegex(flags: Int=0): java.util.regex.Pattern {
public inline fun String.toRegex(flags: Int=0): java.util.regex.Pattern {
return java.util.regex.Pattern.compile(this, flags).sure()
}
/**
Iterator for characters of given CharSequence
*/
inline fun CharSequence.iterator() : CharIterator = object: jet.CharIterator() {
private var index = 0
public inline fun CharSequence.iterator() : CharIterator = object: jet.CharIterator() {
private var index = 0
public override fun nextChar(): Char = get(index++)
public override fun nextChar(): Char = get(index++)
public override val hasNext: Boolean
get() = index < length
public override val hasNext: Boolean
get() = index < length
}
inline fun String.replaceFirst(regex : String, replacement : String) = (this as java.lang.String).replaceFirst(regex, replacement).sure()
public inline fun String.replaceFirst(regex : String, replacement : String) : String = (this as java.lang.String).replaceFirst(regex, replacement).sure()
inline fun String.charAt(index : Int) = (this as java.lang.String).charAt(index).sure()
public inline fun String.charAt(index : Int) : Char = (this as java.lang.String).charAt(index).sure()
inline fun String.split(regex : String, limit : Int) = (this as java.lang.String).split(regex, limit).sure()
public inline fun String.split(regex : String, limit : Int) : Array<String?> = (this as java.lang.String).split(regex, limit).sure()
inline fun String.codePointAt(index : Int) = (this as java.lang.String).codePointAt(index).sure()
public inline fun String.codePointAt(index : Int) : Int = (this as java.lang.String).codePointAt(index).sure()
inline fun String.codePointBefore(index : Int) = (this as java.lang.String).codePointBefore(index).sure()
public inline fun String.codePointBefore(index : Int) : Int = (this as java.lang.String).codePointBefore(index).sure()
inline fun String.codePointCount(beginIndex : Int, endIndex : Int) = (this as java.lang.String).codePointCount(beginIndex, endIndex)
public inline fun String.codePointCount(beginIndex : Int, endIndex : Int) : Int = (this as java.lang.String).codePointCount(beginIndex, endIndex)
inline fun String.compareToIgnoreCase(str : String) = (this as java.lang.String).compareToIgnoreCase(str).sure()
public inline fun String.compareToIgnoreCase(str : String) : Int = (this as java.lang.String).compareToIgnoreCase(str).sure()
inline fun String.concat(str : String) = (this as java.lang.String).concat(str).sure()
public inline fun String.concat(str : String) : String = (this as java.lang.String).concat(str).sure()
inline fun String.contentEquals(cs : CharSequence) = (this as java.lang.String).contentEquals(cs).sure()
public inline fun String.contentEquals(cs : CharSequence) : Boolean = (this as java.lang.String).contentEquals(cs).sure()
inline fun String.contentEquals(sb : StringBuffer) = (this as java.lang.String).contentEquals(sb).sure()
public inline fun String.contentEquals(sb : StringBuffer) : Boolean = (this as java.lang.String).contentEquals(sb).sure()
inline fun String.getBytes(charset : java.nio.charset.Charset) = (this as java.lang.String).getBytes(charset).sure()
public inline fun String.getBytes(charset : java.nio.charset.Charset) : ByteArray = (this as java.lang.String).getBytes(charset).sure()
inline fun String.getBytes(charsetName : String) = (this as java.lang.String).getBytes(charsetName).sure()
public inline fun String.getBytes(charsetName : String) : ByteArray = (this as java.lang.String).getBytes(charsetName).sure()
inline fun String.getChars(srcBegin : Int, srcEnd : Int, dst : CharArray, dstBegin : Int) = (this as java.lang.String).getChars(srcBegin, srcEnd, dst, dstBegin).sure()
public inline fun String.getChars(srcBegin : Int, srcEnd : Int, dst : CharArray, dstBegin : Int) : Tuple0 = (this as java.lang.String).getChars(srcBegin, srcEnd, dst, dstBegin).sure()
inline fun String.indexOf(ch : Char) = (this as java.lang.String).indexOf(ch.toString()).sure()
public inline fun String.indexOf(ch : Char) : Int = (this as java.lang.String).indexOf(ch.toString()).sure()
inline fun String.indexOf(ch : Char, fromIndex : Int) = (this as java.lang.String).indexOf(ch.toString(), fromIndex).sure()
public inline fun String.indexOf(ch : Char, fromIndex : Int) : Int = (this as java.lang.String).indexOf(ch.toString(), fromIndex).sure()
inline fun String.intern() = (this as java.lang.String).intern().sure()
public inline fun String.intern() : String = (this as java.lang.String).intern().sure()
inline fun String.isEmpty() = (this as java.lang.String).isEmpty().sure()
public inline fun String.isEmpty() : Boolean = (this as java.lang.String).isEmpty().sure()
inline fun String.lastIndexOf(ch : Char, fromIndex : Int) = (this as java.lang.String).lastIndexOf(ch.toString(), fromIndex).sure()
public inline fun String.lastIndexOf(ch : Char, fromIndex : Int) : Int = (this as java.lang.String).lastIndexOf(ch.toString(), fromIndex).sure()
inline fun String.lastIndexOf(str : String, fromIndex : Int) = (this as java.lang.String).lastIndexOf(str, fromIndex).sure()
public inline fun String.lastIndexOf(str : String, fromIndex : Int) : Int = (this as java.lang.String).lastIndexOf(str, fromIndex).sure()
inline fun String.matches(regex : String) = (this as java.lang.String).matches(regex).sure()
public inline fun String.matches(regex : String) : Boolean = (this as java.lang.String).matches(regex).sure()
inline fun String.offsetByCodePoints(index : Int, codePointOffset : Int) = (this as java.lang.String).offsetByCodePoints(index, codePointOffset).sure()
public inline fun String.offsetByCodePoints(index : Int, codePointOffset : Int) : Int = (this as java.lang.String).offsetByCodePoints(index, codePointOffset).sure()
inline fun String.regionMatches(ignoreCase : Boolean, toffset : Int, other : String, ooffset : Int, len : Int) = (this as java.lang.String).regionMatches(ignoreCase, toffset, other, ooffset, len).sure()
public inline fun String.regionMatches(ignoreCase : Boolean, toffset : Int, other : String, ooffset : Int, len : Int) : Boolean = (this as java.lang.String).regionMatches(ignoreCase, toffset, other, ooffset, len).sure()
inline fun String.regionMatches(toffset : Int, other : String, ooffset : Int, len : Int) = (this as java.lang.String).regionMatches(toffset, other, ooffset, len).sure()
public inline fun String.regionMatches(toffset : Int, other : String, ooffset : Int, len : Int) : Boolean = (this as java.lang.String).regionMatches(toffset, other, ooffset, len).sure()
inline fun String.replace(target : CharSequence, replacement : CharSequence) = (this as java.lang.String).replace(target, replacement).sure()
public inline fun String.replace(target : CharSequence, replacement : CharSequence) : String = (this as java.lang.String).replace(target, replacement).sure()
inline fun String.subSequence(beginIndex : Int, endIndex : Int) = (this as java.lang.String).subSequence(beginIndex, endIndex).sure()
public inline fun String.subSequence(beginIndex : Int, endIndex : Int) : CharSequence = (this as java.lang.String).subSequence(beginIndex, endIndex).sure()
inline fun String.toLowerCase(locale : java.util.Locale) = (this as java.lang.String).toLowerCase(locale).sure()
public inline fun String.toLowerCase(locale : java.util.Locale) : String = (this as java.lang.String).toLowerCase(locale).sure()
inline fun String.toUpperCase(locale : java.util.Locale) = (this as java.lang.String).toUpperCase(locale).sure()
public inline fun String.toUpperCase(locale : java.util.Locale) : String = (this as java.lang.String).toUpperCase(locale).sure()
/** Returns the string if it is not null or the empty string if its null */
inline fun String?.orEmpty(): String = this ?: ""
public inline fun String?.orEmpty(): String = this ?: ""
// "Extension functions" for CharSequence
inline fun CharSequence.length() = (this as java.lang.CharSequence).length()
public inline fun CharSequence.length() : Int = (this as java.lang.CharSequence).length()
inline val CharSequence.size : Int
get() = length()
inline fun CharSequence.charAt(index : Int) = (this as java.lang.CharSequence).charAt(index)
public inline fun CharSequence.charAt(index : Int) : Char = (this as java.lang.CharSequence).charAt(index)
inline fun CharSequence.get(index : Int) = charAt(index)
public inline fun CharSequence.get(index : Int) : Char = charAt(index)
inline fun CharSequence.subSequence(start : Int, end : Int) = (this as java.lang.CharSequence).subSequence(start, end)
public inline fun CharSequence.subSequence(start : Int, end : Int) : CharSequence? = (this as java.lang.CharSequence).subSequence(start, end)
inline fun CharSequence.get(start : Int, end : Int) = subSequence(start, end)
public inline fun CharSequence.get(start : Int, end : Int) : CharSequence? = subSequence(start, end)
inline fun CharSequence.toString() = (this as java.lang.CharSequence).toString()
public inline fun CharSequence.toString() : String? = (this as java.lang.CharSequence).toString()
@@ -7,9 +7,9 @@ abstract class FunctionalList<T>(public val size: Int) {
val empty : Boolean
get() = size == 0
fun add(element: T) : FunctionalList<T> = FunctionalList.Standard(element, this)
public fun add(element: T) : FunctionalList<T> = FunctionalList.Standard(element, this)
fun reversed() : FunctionalList<T> {
public fun reversed() : FunctionalList<T> {
if(empty)
return this
@@ -23,10 +23,10 @@ abstract class FunctionalList<T>(public val size: Int) {
return new
}
fun iterator() : Iterator<T> = object: Iterator<T> {
public fun iterator() : Iterator<T> = object: Iterator<T> {
var cur = this@FunctionalList
override fun next(): T {
public override fun next(): T {
if(cur.empty)
throw java.util.NoSuchElementException()
@@ -49,9 +49,9 @@ abstract class FunctionalList<T>(public val size: Int) {
class Standard<T>(override val head: T, override val tail: FunctionalList<T>) : FunctionalList<T>(tail.size+1)
fun <T> emptyList() = Empty<T>()
public fun <T> emptyList() : FunctionalList<T> = Empty<T>()
fun <T> of(element: T) : FunctionalList<T> = FunctionalList.Standard<T>(element,emptyList())
public fun <T> of(element: T) : FunctionalList<T> = FunctionalList.Standard<T>(element,emptyList())
}
}
@@ -13,11 +13,11 @@ class FunctionalQueue<T> (
val empty : Boolean
get() = size == 0
fun add(element: T) = FunctionalQueue<T>(input add element, output)
public fun add(element: T) : FunctionalQueue<T> = FunctionalQueue<T>(input add element, output)
fun addFirst(element: T) = FunctionalQueue<T>(input, output add element)
public fun addFirst(element: T) : FunctionalQueue<T> = FunctionalQueue<T>(input, output add element)
fun removeFirst() : #(T,FunctionalQueue<T>) =
public fun removeFirst() : #(T,FunctionalQueue<T>) =
if(output.empty) {
if(input.empty)
throw java.util.NoSuchElementException()
@@ -9,7 +9,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Executes given calculation under lock
Returns result of the calculation
*/
inline fun <erased T> Lock.withLock(action: ()->T) : T {
public inline fun <erased T> Lock.withLock(action: ()->T) : T {
lock()
try {
return action()
@@ -23,7 +23,7 @@ inline fun <erased T> Lock.withLock(action: ()->T) : T {
Executes given calculation under read lock
Returns result of the calculation
*/
inline fun <erased T> ReentrantReadWriteLock.read(action: ()->T) : T {
public inline fun <erased T> ReentrantReadWriteLock.read(action: ()->T) : T {
val rl = readLock().sure()
rl.lock()
try {
@@ -40,7 +40,7 @@ The method does upgrade from read to write lock if needed
If such write has been initiated by checking some condition, the condition must be rechecked inside the action to avoid possible races
Returns result of the calculation
*/
inline fun <erased T> ReentrantReadWriteLock.write(action: ()->T) : T {
public inline fun <erased T> ReentrantReadWriteLock.write(action: ()->T) : T {
val rl = readLock().sure()
val readCount = if (getWriteHoldCount() == 0) getReadHoldCount() else 0
@@ -24,9 +24,9 @@ inline var Thread.contextClassLoader : ClassLoader?
get() = getContextClassLoader()
set(loader: ClassLoader?) { setContextClassLoader(loader) }
fun thread(start: Boolean = true, daemon: Boolean = false, contextClassLoader: ClassLoader? = null, name: String? = null, priority: Int = -1, block: ()->Unit) : Thread {
public fun thread(start: Boolean = true, daemon: Boolean = false, contextClassLoader: ClassLoader? = null, name: String? = null, priority: Int = -1, block: ()->Unit) : Thread {
val thread = object: Thread() {
override fun run() {
public override fun run() {
block()
}
}
@@ -43,9 +43,9 @@ fun thread(start: Boolean = true, daemon: Boolean = false, contextClassLoader: C
return thread
}
inline fun Executor.execute(action: ()->Unit) {
public inline fun Executor.execute(action: ()->Unit) {
execute(object: Runnable{
override fun run() {
public override fun run() {
action()
}
})
+11 -11
View File
@@ -4,68 +4,68 @@ import java.util.Timer
import java.util.TimerTask
import java.util.Date
fun Timer.schedule(delay: Long, action: TimerTask.()->Unit) : TimerTask {
public fun Timer.schedule(delay: Long, action: TimerTask.()->Unit) : TimerTask {
val task = createTask(action)
schedule(task, delay)
return task
}
fun Timer.schedule(time: Date, action: TimerTask.()->Unit) : TimerTask {
public fun Timer.schedule(time: Date, action: TimerTask.()->Unit) : TimerTask {
val task = createTask(action)
schedule(task, time)
return task
}
fun Timer.schedule(delay: Long, period: Long, action: TimerTask.()->Unit) : TimerTask {
public fun Timer.schedule(delay: Long, period: Long, action: TimerTask.()->Unit) : TimerTask {
val task = createTask(action)
schedule(task, delay, period)
return task
}
fun Timer.schedule(time: Date, period: Long, action: TimerTask.()->Unit) : TimerTask {
public fun Timer.schedule(time: Date, period: Long, action: TimerTask.()->Unit) : TimerTask {
val task = createTask(action)
schedule(task, time, period)
return task
}
fun Timer.scheduleAtFixedRate(delay: Long, period: Long, action: TimerTask.()->Unit) : TimerTask {
public fun Timer.scheduleAtFixedRate(delay: Long, period: Long, action: TimerTask.()->Unit) : TimerTask {
val task = createTask(action)
scheduleAtFixedRate(task, delay, period)
return task
}
fun Timer.scheduleAtFixedRate(time: Date, period: Long, action: TimerTask.()->Unit) : TimerTask {
public fun Timer.scheduleAtFixedRate(time: Date, period: Long, action: TimerTask.()->Unit) : TimerTask {
val task = createTask(action)
scheduleAtFixedRate(task, time, period)
return task
}
fun timer(name: String? = null, daemon: Boolean = false, initialDelay: Long = 0.toLong(), period: Long, action: TimerTask.()->Unit) : Timer {
public fun timer(name: String? = null, daemon: Boolean = false, initialDelay: Long = 0.toLong(), period: Long, action: TimerTask.()->Unit) : Timer {
val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.schedule(initialDelay, period, action)
return timer
}
fun timer(name: String? = null, daemon: Boolean = false, startAt: Date, period: Long, action: TimerTask.()->Unit) : Timer {
public fun timer(name: String? = null, daemon: Boolean = false, startAt: Date, period: Long, action: TimerTask.()->Unit) : Timer {
val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.schedule(startAt, period, action)
return timer
}
fun fixedRateTimer(name: String? = null, daemon: Boolean = false, initialDelay: Long = 0.toLong(), period: Long, action: TimerTask.()->Unit) : Timer {
public fun fixedRateTimer(name: String? = null, daemon: Boolean = false, initialDelay: Long = 0.toLong(), period: Long, action: TimerTask.()->Unit) : Timer {
val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.scheduleAtFixedRate(initialDelay, period, action)
return timer
}
fun fixedRateTimer(name: String? = null, daemon: Boolean = false, startAt: Date, period : Long, action: TimerTask.()->Unit) : Timer {
public fun fixedRateTimer(name: String? = null, daemon: Boolean = false, startAt: Date, period : Long, action: TimerTask.()->Unit) : Timer {
val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.scheduleAtFixedRate(startAt, period, action)
return timer
}
private fun createTask(action: TimerTask.()->Unit) : TimerTask = object: TimerTask() {
override fun run() {
public override fun run() {
action()
}
}
+36 -36
View File
@@ -96,7 +96,7 @@ set(value) {
// Helper methods
/** Returns true if the element has the given CSS class style in its 'class' attribute */
fun Element.hasClass(cssClass: String): Boolean {
public fun Element.hasClass(cssClass: String): Boolean {
val c = this.classes
return if (c != null)
c.matches("""(^|.*\s+)$cssClass($|\s+.*)""")
@@ -104,7 +104,7 @@ fun Element.hasClass(cssClass: String): Boolean {
}
/** Adds the given CSS class to this element's 'class' attribute */
fun Element.addClass(cssClass: String): Boolean {
public fun Element.addClass(cssClass: String): Boolean {
val classSet = this.classSet
val answer = classSet.add(cssClass)
if (answer) {
@@ -114,7 +114,7 @@ fun Element.addClass(cssClass: String): Boolean {
}
/** Removes the given CSS class to this element's 'class' attribute */
fun Element.removeClass(cssClass: String): Boolean {
public fun Element.removeClass(cssClass: String): Boolean {
val classSet = this.classSet
val answer = classSet.remove(cssClass)
if (answer) {
@@ -125,7 +125,7 @@ fun Element.removeClass(cssClass: String): Boolean {
/** TODO this approach generates compiler errors...
fun Element.addClass(varargs cssClasses: Array<String>): Boolean {
public fun Element.addClass(varargs cssClasses: Array<String>): Boolean {
val set = this.classSet
var answer = false
for (cs in cssClasses) {
@@ -139,7 +139,7 @@ fun Element.addClass(varargs cssClasses: Array<String>): Boolean {
return answer
}
fun Element.removeClass(varargs cssClasses: Array<String>): Boolean {
public fun Element.removeClass(varargs cssClasses: Array<String>): Boolean {
val set = this.classSet
var answer = false
for (cs in cssClasses) {
@@ -155,7 +155,7 @@ fun Element.removeClass(varargs cssClasses: Array<String>): Boolean {
*/
/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
fun Document?.get(selector: String): List<Element> {
public fun Document?.get(selector: String): List<Element> {
val root = this?.getDocumentElement()
return if (root != null) {
if (selector == "*") {
@@ -179,7 +179,7 @@ fun Document?.get(selector: String): List<Element> {
}
/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
fun Element.get(selector: String): List<Element> {
public fun Element.get(selector: String): List<Element> {
return if (selector == "*") {
elements
} else if (selector.startsWith(".")) {
@@ -197,11 +197,11 @@ fun Element.get(selector: String): List<Element> {
}
/** Returns an [[Iterator]] over the next siblings of this node */
fun Node.nextSiblings() : Iterator<Node> = NextSiblingIterator(this)
public fun Node.nextSiblings() : Iterator<Node> = NextSiblingIterator(this)
class NextSiblingIterator(var node: Node) : AbstractIterator<Node>() {
override fun computeNext(): Node? {
public override fun computeNext(): Node? {
val next = node.getNextSibling()
if (next != null) {
node = next
@@ -213,11 +213,11 @@ class NextSiblingIterator(var node: Node) : AbstractIterator<Node>() {
}
}
/** Returns an [[Iterator]] over the next siblings of this node */
fun Node.previousSiblings() : Iterator<Node> = PreviousSiblingIterator(this)
public fun Node.previousSiblings() : Iterator<Node> = PreviousSiblingIterator(this)
class PreviousSiblingIterator(var node: Node) : AbstractIterator<Node>() {
override fun computeNext(): Node? {
public override fun computeNext(): Node? {
val next = node.getPreviousSibling()
if (next != null) {
node = next
@@ -230,24 +230,24 @@ class PreviousSiblingIterator(var node: Node) : AbstractIterator<Node>() {
}
/** Returns true if this node is a Text node or a CDATA node */
fun Node.isText(): Boolean {
public fun Node.isText(): Boolean {
val nodeType = getNodeType()
return nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE
}
/** Returns an [[Iterator]] of all the next [[Element]] siblings */
fun Node.nextElements(): Iterator<Element> = nextSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
public fun Node.nextElements(): Iterator<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>())
public fun Node.previousElements(): Iterator<Element> = previousSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
/** Returns the attribute value or empty string if its not present */
inline fun Element.attribute(name: String): String {
public inline fun Element.attribute(name: String): String {
return this.getAttribute(name) ?: ""
}
/** Returns the children of the element as a list */
inline fun Element?.children(): List<Node> {
public inline fun Element?.children(): List<Node> {
return this?.getChildNodes().toList()
}
@@ -261,22 +261,22 @@ get() = this?.getElementsByTagName("*").toElementList()
/** Returns all the child elements given the local element name */
inline fun Element?.elements(localName: String?): List<Element> {
public inline fun Element?.elements(localName: String?): List<Element> {
return this?.getElementsByTagName(localName).toElementList()
}
/** Returns all the elements given the local element name */
inline fun Document?.elements(localName: String?): List<Element> {
public inline fun Document?.elements(localName: String?): List<Element> {
return this?.getElementsByTagName(localName).toElementList()
}
/** Returns all the child elements given the namespace URI and local element name */
inline fun Element?.elements(namespaceUri: String?, localName: String?): List<Element> {
public inline fun Element?.elements(namespaceUri: String?, localName: String?): List<Element> {
return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
}
/** Returns all the elements given the namespace URI and local element name */
inline fun Document?.elements(namespaceUri: String?, localName: String?): List<Element> {
public inline fun Document?.elements(namespaceUri: String?, localName: String?): List<Element> {
return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
}
@@ -300,7 +300,7 @@ val NodeList?.last : Node?
get() = this.tail
inline fun NodeList?.toList(): List<Node> {
public inline fun NodeList?.toList(): List<Node> {
return if (this == null) {
Collections.EMPTY_LIST as List<Node>
}
@@ -309,7 +309,7 @@ inline fun NodeList?.toList(): List<Node> {
}
}
inline fun NodeList?.toElementList(): List<Element> {
public inline fun NodeList?.toElementList(): List<Element> {
return if (this == null) {
Collections.EMPTY_LIST as List<Element>
}
@@ -319,7 +319,7 @@ inline fun NodeList?.toElementList(): List<Element> {
}
/** Converts the node list to an XML String */
fun NodeList?.toXmlString(xmlDeclaration: Boolean = false): String {
public fun NodeList?.toXmlString(xmlDeclaration: Boolean = false): String {
return if (this == null)
"" else {
nodesToXmlString(this.toList(), xmlDeclaration)
@@ -327,7 +327,7 @@ fun NodeList?.toXmlString(xmlDeclaration: Boolean = false): String {
}
class NodeListAsList(val nodeList: NodeList): AbstractList<Node>() {
override fun get(index: Int): Node {
public override fun get(index: Int): Node {
val node = nodeList.item(index)
if (node == null) {
throw IndexOutOfBoundsException("NodeList does not contain a node at index: " + index)
@@ -336,11 +336,11 @@ class NodeListAsList(val nodeList: NodeList): AbstractList<Node>() {
}
}
override fun size(): Int = nodeList.getLength()
public override fun size(): Int = nodeList.getLength()
}
class ElementListAsList(val nodeList: NodeList): AbstractList<Element>() {
override fun get(index: Int): Element {
public override fun get(index: Int): Element {
val node = nodeList.item(index)
if (node is Element) {
return node
@@ -353,23 +353,23 @@ class ElementListAsList(val nodeList: NodeList): AbstractList<Element>() {
}
}
override fun size(): Int = nodeList.getLength()
public override fun size(): Int = nodeList.getLength()
}
// Syntax sugar
inline fun Node.plus(child: Node?): Node {
public inline fun Node.plus(child: Node?): Node {
if (child != null) {
this.appendChild(child)
}
return this
}
inline fun Element.plus(text: String?): Element = this.addText(text)
public inline fun Element.plus(text: String?): Element = this.addText(text)
inline fun Element.plusAssign(text: String?): Element = this.addText(text)
public inline fun Element.plusAssign(text: String?): Element = this.addText(text)
// Builder
@@ -377,7 +377,7 @@ inline fun Element.plusAssign(text: String?): Element = this.addText(text)
/**
* Creates a new element which can be configured via a function
*/
fun Document.createElement(name: String, init: Element.()-> Unit): Element {
public fun Document.createElement(name: String, init: Element.()-> Unit): Element {
val elem = this.createElement(name).sure()
elem.init()
return elem
@@ -386,14 +386,14 @@ fun Document.createElement(name: String, init: Element.()-> Unit): Element {
/**
* Creates a new element to an element which has an owner Document which can be configured via a function
*/
fun Element.createElement(name: String, doc: Document? = null, init: Element.()-> Unit): Element {
public fun Element.createElement(name: String, doc: Document? = null, init: Element.()-> Unit): Element {
val elem = ownerDocument(doc).createElement(name).sure()
elem.init()
return elem
}
/** Returns the owner document of the element or uses the provided document */
fun Node.ownerDocument(doc: Document? = null): Document {
public fun Node.ownerDocument(doc: Document? = null): Document {
val answer = if (this is Document) this as Document
else if (doc == null) this.getOwnerDocument()
else doc
@@ -408,7 +408,7 @@ fun Node.ownerDocument(doc: Document? = null): Document {
/**
Adds a newly created element which can be configured via a function
*/
fun Document.addElement(name: String, init: Element.()-> Unit): Element {
public fun Document.addElement(name: String, init: Element.()-> Unit): Element {
val child = createElement(name, init)
this.appendChild(child)
return child
@@ -417,7 +417,7 @@ fun Document.addElement(name: String, init: Element.()-> Unit): Element {
/**
Adds a newly created element to an element which has an owner Document which can be configured via a function
*/
fun Element.addElement(name: String, doc: Document? = null, init: Element.()-> Unit): Element {
public fun Element.addElement(name: String, doc: Document? = null, init: Element.()-> Unit): Element {
val child = createElement(name, doc, init)
this.appendChild(child)
return child
@@ -426,7 +426,7 @@ fun Element.addElement(name: String, doc: Document? = null, init: Element.()-> U
/**
Adds a newly created text node to an element which either already has an owner Document or one must be provided as a parameter
*/
fun Element.addText(text: String?, doc: Document? = null): Element {
public fun Element.addText(text: String?, doc: Document? = null): Element {
if (text != null) {
val child = ownerDocument(doc).createTextNode(text)
this.appendChild(child)
+6 -6
View File
@@ -20,17 +20,17 @@ import java.util.Collection
import java.io.Writer
/** Creates a new document with the given document builder*/
fun createDocument(builder: DocumentBuilder): Document {
public fun createDocument(builder: DocumentBuilder): Document {
return builder.newDocument().sure()
}
/** Creates a new document with an optional DocumentBuilderFactory */
fun createDocument(builderFactory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance().sure()): Document {
public fun createDocument(builderFactory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance().sure()): Document {
return createDocument(builderFactory.newDocumentBuilder().sure())
}
/** Creates a new TrAX transformer */
fun createTransformer(source: Source? = null, factory: TransformerFactory = TransformerFactory.newInstance().sure()): Transformer {
public fun createTransformer(source: Source? = null, factory: TransformerFactory = TransformerFactory.newInstance().sure()): Transformer {
val transformer = if (source != null) {
factory.newTransformer(source)
} else {
@@ -40,21 +40,21 @@ fun createTransformer(source: Source? = null, factory: TransformerFactory = Tran
}
/** Converts the node to an XML String */
fun Node.toXmlString(xmlDeclaration: Boolean = false): String {
public fun Node.toXmlString(xmlDeclaration: Boolean = false): String {
val writer = StringWriter()
writeXmlString(writer, xmlDeclaration)
return writer.toString().sure()
}
/** Converts the node to an XML String and writes it to the given [[Writer]] */
fun Node.writeXmlString(writer: Writer, xmlDeclaration: Boolean): Unit {
public fun Node.writeXmlString(writer: Writer, xmlDeclaration: Boolean): Unit {
val transformer = createTransformer()
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, if (xmlDeclaration) "no" else "yes")
transformer.transform(DOMSource(this), StreamResult(writer))
}
/** Converts the collection of nodes to an XML String */
fun nodesToXmlString(nodes: Iterable<Node>, xmlDeclaration: Boolean = false): String {
public fun nodesToXmlString(nodes: Iterable<Node>, xmlDeclaration: Boolean = false): String {
// TODO this should work...
// return this.map<Node,String>{it.toXmlString()}.join("")
val builder = StringBuilder()
+72 -72
View File
@@ -17,134 +17,134 @@ public val defaultCharset: Charset = Charset.forName("UTF-8").sure()
/** Prints the given message to [[System.out]] */
inline fun print(message : Any?) {
public inline fun print(message : Any?) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Int) {
public inline fun print(message : Int) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Long) {
public inline fun print(message : Long) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Byte) {
public inline fun print(message : Byte) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Short) {
public inline fun print(message : Short) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Char) {
public inline fun print(message : Char) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Boolean) {
public inline fun print(message : Boolean) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Float) {
public inline fun print(message : Float) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : Double) {
public inline fun print(message : Double) {
System.out?.print(message)
}
/** Prints the given message to [[System.out]] */
inline fun print(message : CharArray) {
public inline fun print(message : CharArray) {
System.out?.print(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Any?) {
public inline fun println(message : Any?) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Int) {
public inline fun println(message : Int) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Long) {
public inline fun println(message : Long) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Byte) {
public inline fun println(message : Byte) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Short) {
public inline fun println(message : Short) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Char) {
public inline fun println(message : Char) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Boolean) {
public inline fun println(message : Boolean) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Float) {
public inline fun println(message : Float) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : Double) {
public inline fun println(message : Double) {
System.out?.println(message)
}
/** Prints the given message and newline to [[System.out]] */
inline fun println(message : CharArray) {
public inline fun println(message : CharArray) {
System.out?.println(message)
}
/** Prints a newline t[[System.out]] */
inline fun println() {
public inline fun println() {
System.out?.println()
}
private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : InputStream() {
override fun read() : Int {
public override fun read() : Int {
return System.`in`?.read() ?: -1
}
override fun reset() {
public override fun reset() {
System.`in`?.reset()
}
override fun read(b: ByteArray?): Int {
public override fun read(b: ByteArray?): Int {
return System.`in`?.read(b) ?: -1
}
override fun close() {
public override fun close() {
System.`in`?.close()
}
override fun mark(readlimit: Int) {
public override fun mark(readlimit: Int) {
System.`in`?.mark(readlimit)
}
override fun skip(n: Long): Long {
public override fun skip(n: Long): Long {
return System.`in`?.skip(n) ?: -1.toLong()
}
override fun available(): Int {
public override fun available(): Int {
return System.`in`?.available() ?: 0
}
override fun markSupported(): Boolean {
public override fun markSupported(): Boolean {
return System.`in`?.markSupported() ?: false
}
override fun read(b: ByteArray?, off: Int, len: Int): Int {
public override fun read(b: ByteArray?, off: Int, len: Int): Int {
return System.`in`?.read(b, off, len) ?: -1
}
}))
/** Reads a line of input from [[System.in]] */
inline fun readLine() : String? = stdin.readLine()
public inline fun readLine() : String? = stdin.readLine()
/** Uses the given resource then closes it down correctly whether an exception is thrown or not */
inline fun <T: Closeable, R> T.use(block: (T)-> R) : R {
public inline fun <T: Closeable, R> T.use(block: (T)-> R) : R {
var closed = false
try {
return block(this)
@@ -170,47 +170,47 @@ inline fun <T: Closeable, R> T.use(block: (T)-> R) : R {
}
/** Returns an [Iterator] of bytes over an input stream */
fun InputStream.iterator() : ByteIterator =
public fun InputStream.iterator() : ByteIterator =
object: ByteIterator() {
override val hasNext : Boolean
get() = available() > 0
override fun nextByte() = read().toByte()
public override fun nextByte() : Byte = read().toByte()
}
/** Creates a buffered input stream */
inline fun InputStream.buffered(bufferSize: Int = defaultBufferSize)
= if (this is BufferedInputStream)
this
else
BufferedInputStream(this, bufferSize)
public inline fun InputStream.buffered(bufferSize: Int = defaultBufferSize) : InputStream
= if (this is BufferedInputStream)
this
else
BufferedInputStream(this, bufferSize)
inline fun InputStream.reader(encoding: Charset = defaultCharset) : InputStreamReader = InputStreamReader(this, encoding)
public inline fun InputStream.reader(encoding: Charset = defaultCharset) : InputStreamReader = InputStreamReader(this, encoding)
inline fun InputStream.reader(encoding: String) = InputStreamReader(this, encoding)
public inline fun InputStream.reader(encoding: String) : InputStreamReader = InputStreamReader(this, encoding)
inline fun InputStream.reader(encoding: CharsetDecoder) = InputStreamReader(this, encoding)
public inline fun InputStream.reader(encoding: CharsetDecoder) : InputStreamReader = InputStreamReader(this, encoding)
inline fun OutputStream.buffered(bufferSize: Int = defaultBufferSize) : BufferedOutputStream
= if (this is BufferedOutputStream) this else BufferedOutputStream(this, bufferSize)
public inline fun OutputStream.buffered(bufferSize: Int = defaultBufferSize) : BufferedOutputStream
= if (this is BufferedOutputStream) this else BufferedOutputStream(this, bufferSize)
inline fun OutputStream.writer(encoding: Charset = defaultCharset) : OutputStreamWriter = OutputStreamWriter(this, encoding)
public inline fun OutputStream.writer(encoding: Charset = defaultCharset) : OutputStreamWriter = OutputStreamWriter(this, encoding)
inline fun OutputStream.writer(encoding: String) = OutputStreamWriter(this, encoding)
public inline fun OutputStream.writer(encoding: String) : OutputStreamWriter = OutputStreamWriter(this, encoding)
inline fun OutputStream.writer(encoding: CharsetEncoder) = OutputStreamWriter(this, encoding)
public inline fun OutputStream.writer(encoding: CharsetEncoder) : OutputStreamWriter = OutputStreamWriter(this, encoding)
inline fun Reader.buffered(bufferSize: Int = defaultBufferSize): BufferedReader
= if(this is BufferedReader) this else BufferedReader(this, bufferSize)
public inline fun Reader.buffered(bufferSize: Int = defaultBufferSize): BufferedReader
= if(this is BufferedReader) this else BufferedReader(this, bufferSize)
inline fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter
= if(this is BufferedWriter) this else BufferedWriter(this, bufferSize)
public inline fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter
= if(this is BufferedWriter) this else BufferedWriter(this, bufferSize)
inline fun Reader.forEachLine(block: (String) -> Unit): Unit {
public inline fun Reader.forEachLine(block: (String) -> Unit): Unit {
this.use{
val iter = buffered().lineIterator()
while (iter.hasNext) {
@@ -220,7 +220,7 @@ inline fun Reader.forEachLine(block: (String) -> Unit): Unit {
}
}
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: (Iterator<String>) -> T): T = this.buffered().use<BufferedReader, T>{block(it.lineIterator())}
/**
* Returns an iterator over each line.
@@ -230,7 +230,7 @@ inline fun <T> Reader.useLines(block: (Iterator<String>) -> T): T = this.buffere
* <br>
* We suggest you try the method useLines() instead which closes the stream when the processing is complete.
*/
inline fun BufferedReader.lineIterator() : Iterator<String> = LineIterator(this)
public inline fun BufferedReader.lineIterator() : Iterator<String> = LineIterator(this)
class LineIterator(val reader: BufferedReader) : Iterator<String> {
private var nextValue: String? = null
@@ -245,7 +245,7 @@ class LineIterator(val reader: BufferedReader) : Iterator<String> {
return nextValue != null
}
override fun next(): String {
public override fun next(): String {
if (!hasNext) {
throw NoSuchElementException()
}
@@ -260,7 +260,7 @@ class LineIterator(val reader: BufferedReader) : Iterator<String> {
/**
* Recursively process this file and all children with the given block
*/
fun File.recurse(block: (File) -> Unit): Unit {
public fun File.recurse(block: (File) -> Unit): Unit {
block(this)
if (this.isDirectory()) {
for (child in this.listFiles()) {
@@ -312,14 +312,14 @@ get() {
/**
* Returns true if the given file is in the same directory or a descendant directory
*/
fun File.isDescendant(file: File): Boolean {
public fun File.isDescendant(file: File): Boolean {
return file.directory.canonicalPath.startsWith(this.directory.canonicalPath)
}
/**
* Returns the relative path of the given descendant of this file if its a descendant
*/
fun File.relativePath(descendant: File): String {
public fun File.relativePath(descendant: File): String {
val prefix = this.directory.canonicalPath
val answer = descendant.canonicalPath
return if (answer.startsWith(prefix)) {
@@ -334,14 +334,14 @@ fun File.relativePath(descendant: File): String {
*
* This method is not recommended on huge files.
*/
fun File.readBytes(): ByteArray {
public fun File.readBytes(): ByteArray {
return FileInputStream(this).use<FileInputStream,ByteArray>{ it.readBytes(this.length().toInt()) }
}
/**
* Writes the bytes as the contents of the file
*/
fun File.writeBytes(data: ByteArray): Unit {
public fun File.writeBytes(data: ByteArray): Unit {
return FileOutputStream(this).use<FileOutputStream,Unit>{ it.write(data) }
}
/**
@@ -351,7 +351,7 @@ fun File.writeBytes(data: ByteArray): Unit {
*
* This method is not recommended on huge files.
*/
fun File.readText(encoding:String? = null) = readBytes().toString(encoding)
public fun File.readText(encoding:String? = null) : String = readBytes().toString(encoding)
/**
* Reads the entire content of the file as a String using the
@@ -359,26 +359,26 @@ fun File.readText(encoding:String? = null) = readBytes().toString(encoding)
*
* This method is not recommended on huge files.
*/
fun File.readText(encoding:Charset) = readBytes().toString(encoding)
public fun File.readText(encoding:Charset) : String = readBytes().toString(encoding)
/**
* Writes the text as the contents of the file using the optional
* character encoding. The default platform encoding is used if the character
* encoding is not specified or null.
*/
fun File.writeText(text: String, encoding:String?=null): Unit { writeBytes(text.toByteArray(encoding)) }
public fun File.writeText(text: String, encoding:String?=null): Unit { writeBytes(text.toByteArray(encoding)) }
/**
* Writes the text as the contents of the file using the optional
* character encoding. The default platform encoding is used if the character
* encoding is not specified or null.
*/
fun File.writeText(text: String, encoding:Charset): Unit { writeBytes(text.toByteArray(encoding)) }
public fun File.writeText(text: String, encoding:Charset): Unit { writeBytes(text.toByteArray(encoding)) }
/**
* Copies this file to the given output file, returning the number of bytes copied
*/
fun File.copyTo(file: File, bufferSize: Int = defaultBufferSize): Long {
public fun File.copyTo(file: File, bufferSize: Int = defaultBufferSize): Long {
file.directory.mkdirs()
val input = FileInputStream(this)
return input.use<FileInputStream,Long>{
@@ -394,7 +394,7 @@ fun File.copyTo(file: File, bufferSize: Int = defaultBufferSize): Long {
*
* **Note** it is the callers responsibility to close this resource
*/
fun InputStream.readBytes(estimatedSize: Int = defaultBufferSize): ByteArray {
public fun InputStream.readBytes(estimatedSize: Int = defaultBufferSize): ByteArray {
val buffer = ByteArrayOutputStream(estimatedSize)
this.copyTo(buffer)
return buffer.toByteArray().sure()
@@ -405,7 +405,7 @@ fun InputStream.readBytes(estimatedSize: Int = defaultBufferSize): ByteArray {
*
* **Note** it is the callers responsibility to close this resource
*/
fun Reader.readText(): String {
public fun Reader.readText(): String {
val buffer = StringWriter()
copyTo(buffer)
return buffer.toString().sure()
@@ -416,7 +416,7 @@ fun Reader.readText(): String {
*
* **Note** it is the callers responsibility to close both of these resources
*/
fun InputStream.copyTo(out: OutputStream, bufferSize: Int = defaultBufferSize): Long {
public fun InputStream.copyTo(out: OutputStream, bufferSize: Int = defaultBufferSize): Long {
var bytesCopied: Long = 0
val buffer = ByteArray(bufferSize)
var bytes = read(buffer)
@@ -433,7 +433,7 @@ fun InputStream.copyTo(out: OutputStream, bufferSize: Int = defaultBufferSize):
*
* **Note** it is the callers responsibility to close both of these resources
*/
fun Reader.copyTo(out: Writer, bufferSize: Int = defaultBufferSize): Long {
public fun Reader.copyTo(out: Writer, bufferSize: Int = defaultBufferSize): Long {
var charsCopied: Long = 0
val buffer = CharArray(bufferSize)
var chars = read(buffer)
@@ -450,19 +450,19 @@ fun Reader.copyTo(out: Writer, bufferSize: Int = defaultBufferSize): Long {
*
* This method is not recommended on huge files.
*/
fun URL.readText(encoding: String? = null): String = readBytes().toString(encoding)
public fun URL.readText(encoding: String? = null): String = readBytes().toString(encoding)
/**
* Reads the entire content of the URL as a String with the specified character encoding.
*
* This method is not recommended on huge files.
*/
fun URL.readText(encoding: Charset): String = readBytes().toString(encoding)
public fun URL.readText(encoding: Charset): String = readBytes().toString(encoding)
/**
* Reads the entire content of the URL as bytes
*
* This method is not recommended on huge files.
*/
fun URL.readBytes(): ByteArray = this.openStream().sure().use<InputStream,ByteArray>{ it.readBytes() }
public fun URL.readBytes(): ByteArray = this.openStream().sure().use<InputStream,ByteArray>{ it.readBytes() }
+11 -11
View File
@@ -3,25 +3,25 @@ package kotlin.math
import java.math.BigInteger
import java.math.BigDecimal
fun BigInteger.plus(other: BigInteger) = this.add(other).sure()
public fun BigInteger.plus(other: BigInteger) : BigInteger = this.add(other).sure()
fun BigInteger.minus(other: BigInteger) = this.subtract(other).sure()
public fun BigInteger.minus(other: BigInteger) : BigInteger = this.subtract(other).sure()
fun BigInteger.times(other: BigInteger) = this.multiply(other).sure()
public fun BigInteger.times(other: BigInteger) : BigInteger = this.multiply(other).sure()
fun BigInteger.div(other: BigInteger) = this.divide(other).sure()
public fun BigInteger.div(other: BigInteger) : BigInteger = this.divide(other).sure()
fun BigInteger.minus() = this.negate().sure()
public fun BigInteger.minus() : BigInteger = this.negate().sure()
fun BigDecimal.plus(other: BigDecimal) = this.add(other).sure()
public fun BigDecimal.plus(other: BigDecimal) : BigDecimal = this.add(other).sure()
fun BigDecimal.minus(other: BigDecimal) = this.subtract(other).sure()
public fun BigDecimal.minus(other: BigDecimal) : BigDecimal = this.subtract(other).sure()
fun BigDecimal.times(other: BigDecimal) = this.multiply(other).sure()
public fun BigDecimal.times(other: BigDecimal) : BigDecimal = this.multiply(other).sure()
fun BigDecimal.div(other: BigDecimal) = this.divide(other).sure()
public fun BigDecimal.div(other: BigDecimal) : BigDecimal = this.divide(other).sure()
fun BigDecimal.mod(other: BigDecimal) = this.remainder(other).sure()
public fun BigDecimal.mod(other: BigDecimal) : BigDecimal = this.remainder(other).sure()
fun BigDecimal.minus() = this.negate().sure()
public fun BigDecimal.minus() : BigDecimal = this.negate().sure()
@@ -3,20 +3,20 @@ package kotlin.modules
import java.util.*
import jet.modules.*
fun module(name: String, callback: ModuleBuilder.() -> Unit) {
public fun module(name: String, callback: ModuleBuilder.() -> Unit) {
val builder = ModuleBuilder(name)
builder.callback()
AllModules.modules.sure().get()?.add(builder)
}
class SourcesBuilder(val parent: ModuleBuilder) {
fun plusAssign(pattern: String) {
public fun plusAssign(pattern: String) {
parent.addSourceFiles(pattern)
}
}
class ClasspathBuilder(val parent: ModuleBuilder) {
fun plusAssign(name: String) {
public fun plusAssign(name: String) {
parent.addClasspathEntry(name)
}
}
@@ -32,16 +32,16 @@ open class ModuleBuilder(val name: String): Module {
val classpath: ClasspathBuilder
get() = ClasspathBuilder(this)
fun addSourceFiles(pattern: String) {
public fun addSourceFiles(pattern: String) {
sourceFiles0.add(pattern)
}
fun addClasspathEntry(name: String) {
public fun addClasspathEntry(name: String) {
classpathRoots0.add(name)
}
override fun getSourceFiles(): List<String?>? = sourceFiles0
override fun getClasspathRoots(): List<String?>? = classpathRoots0
override fun getModuleName(): String? = name
public override fun getSourceFiles(): List<String?>? = sourceFiles0
public override fun getClasspathRoots(): List<String?>? = classpathRoots0
public override fun getModuleName(): String? = name
}
@@ -3,40 +3,40 @@ package kotlin.nullable
import java.util.*
/** Returns true if the element is not null and matches the given predicate */
inline fun <T> T?.any(predicate: (T)-> Boolean): Boolean {
public inline fun <T> T?.any(predicate: (T)-> Boolean): Boolean {
return this != null && predicate(this)
}
/** Returns true if the element is not null and matches the given predicate */
inline fun <T> T?.all(predicate: (T)-> Boolean): Boolean {
public inline fun <T> T?.all(predicate: (T)-> Boolean): Boolean {
return this != null && predicate(this)
}
/** Returns the 1 if the element is not null else 0 */
inline fun <T> T?.count(predicate: (T)-> Boolean): Int {
public inline fun <T> T?.count(predicate: (T)-> Boolean): Int {
return if (this != null) 1 else 0
}
/** Returns the first item which matches the predicate if this element is not null else null */
inline fun <T> T?.find(predicate: (T)-> Boolean): T? {
public inline fun <T> T?.find(predicate: (T)-> Boolean): T? {
return if (this != null && predicate(this)) this else null
}
/** Returns a new List containing all elements in this collection which match the given predicate */
inline fun <T> T?.filter(predicate: (T)-> Boolean): T? = find(predicate)
public inline fun <T> T?.filter(predicate: (T)-> Boolean): T? = find(predicate)
/** Filters all elements in this collection which match the given predicate into the given result collection */
inline fun <T, C: Collection<in T>> T?.filterTo(result: C, predicate: (T)-> Boolean): C {
public inline fun <T, C: Collection<in T>> T?.filterTo(result: C, predicate: (T)-> Boolean): C {
if (this != null && predicate(this))
result.add(this)
return result
}
/** Returns a List containing all the non null elements in this collection */
inline fun <T> T?.filterNotNull(): Collection<T> = filterNotNullTo(java.util.ArrayList<T>())
public inline fun <T> T?.filterNotNull(): Collection<T> = filterNotNullTo(java.util.ArrayList<T>())
/** Filters all the null elements in this collection winto the given result collection */
inline fun <T, C: Collection<in T>> T?.filterNotNullTo(result: C): C {
public inline fun <T, C: Collection<in T>> T?.filterNotNullTo(result: C): C {
if (this != null) {
result.add(this)
}
@@ -44,10 +44,10 @@ inline fun <T, C: Collection<in T>> T?.filterNotNullTo(result: C): C {
}
/** Returns a new collection containing all elements in this collection which do not match the given predicate */
inline fun <T> T?.filterNot(predicate: (T)-> Boolean): Collection<T> = filterNotTo(ArrayList<T>(), predicate)
public inline fun <T> T?.filterNot(predicate: (T)-> Boolean): Collection<T> = filterNotTo(ArrayList<T>(), predicate)
/** Returns a new collection containing all elements in this collection which do not match the given predicate */
inline fun <T, C: Collection<in T>> T?.filterNotTo(result: C, predicate: (T)-> Boolean): C {
public inline fun <T, C: Collection<in T>> T?.filterNotTo(result: C, predicate: (T)-> Boolean): C {
if (this != null && !predicate(this)) {
result.add(this)
}
@@ -58,7 +58,7 @@ inline fun <T, C: Collection<in T>> T?.filterNotTo(result: C, predicate: (T)-> B
* Returns the result of transforming each item in the collection to a one or more values which
* are concatenated together into a single collection
*/
inline fun <T, R> T?.flatMap(transform: (T)-> Collection<R>): Collection<R> {
public inline fun <T, R> T?.flatMap(transform: (T)-> Collection<R>): Collection<R> {
return flatMapTo(ArrayList<R>(), transform)
}
@@ -66,7 +66,7 @@ inline fun <T, R> T?.flatMap(transform: (T)-> Collection<R>): Collection<R> {
* Returns the result of transforming each item in the collection to a one or more values which
* are concatenated together into a single collection
*/
inline fun <T, R> T?.flatMapTo(result: Collection<R>, transform: (T)-> Collection<R>): Collection<R> {
public inline fun <T, R> T?.flatMapTo(result: Collection<R>, transform: (T)-> Collection<R>): Collection<R> {
if (this != null) {
val coll = transform(this)
if (coll != null) {
@@ -79,7 +79,7 @@ inline fun <T, R> T?.flatMapTo(result: Collection<R>, transform: (T)-> Collectio
}
/** Performs the given operation on each element inside the collection */
inline fun <T> T?.forEach(operation: (element: T) -> Unit) {
public inline fun <T> T?.forEach(operation: (element: T) -> Unit) {
if (this != null) {
operation(this)
}
@@ -91,7 +91,7 @@ inline fun <T> T?.forEach(operation: (element: T) -> Unit) {
* For example to sum together all numeric values in a collection of numbers it would be
* {code}val total = numbers.fold(0){(a, b) -> a + b}{code}
*/
inline fun <T> T?.fold(initial: T, operation: (it: T, it2: T) -> T): T {
public inline fun <T> T?.fold(initial: T, operation: (it: T, it2: T) -> T): T {
return if (this != null) {
operation(initial, this)
} else {
@@ -102,7 +102,7 @@ inline fun <T> T?.fold(initial: T, operation: (it: T, it2: T) -> T): T {
/**
* Folds all the values from right to left with the initial value to perform the operation on sequential pairs of values
*/
inline fun <T> T?.foldRight(initial: T, operation: (it: T, it2: T) -> T): T {
public inline fun <T> T?.foldRight(initial: T, operation: (it: T, it2: T) -> T): T {
// maximum size is 1 so it makes no difference :)
return fold(initial, operation)
}
@@ -111,7 +111,7 @@ inline fun <T> T?.foldRight(initial: T, operation: (it: T, it2: T) -> T): T {
* Iterates through the collection performing the transformation on each element and using the result
* as the key in a map to group elements by the result
*/
inline fun <T, K> T?.groupBy(result: Map<K, List<T>> = HashMap<K, List<T>>(), toKey: (T)-> K): Map<K, List<T>> {
public inline fun <T, K> T?.groupBy(result: Map<K, List<T>> = HashMap<K, List<T>>(), toKey: (T)-> K): Map<K, List<T>> {
if (this != null) {
val key = toKey(this)
val list = result.getOrPut(key){ ArrayList<T>() }
@@ -122,7 +122,7 @@ inline fun <T, K> T?.groupBy(result: Map<K, List<T>> = HashMap<K, List<T>>(), to
/** Creates a String from the nullable or item with the given prefix and postfix if supplied */
inline fun <T> T?.join(separator: String, prefix: String = "", postfix: String = ""): String {
public inline fun <T> T?.join(separator: String, prefix: String = "", postfix: String = ""): String {
val buffer = StringBuilder(prefix)
var first = true
if (this != null) {
@@ -134,7 +134,7 @@ inline fun <T> T?.join(separator: String, prefix: String = "", postfix: String =
/** Returns the nullable result of transforming this with the given transformation function */
inline fun <T, R> T?.map(transform : (T) -> R) : R? {
public inline fun <T, R> T?.map(transform : (T) -> R) : R? {
return if (this != null) {
transform(this)
} else {
@@ -143,7 +143,7 @@ inline fun <T, R> T?.map(transform : (T) -> R) : R? {
}
/** Transforms each element of this collection with the given function then adds the results to the given collection */
inline fun <T, R, C: Collection<in R>> T?.mapTo(result: C, transform : (T) -> R) : C {
public inline fun <T, R, C: Collection<in R>> T?.mapTo(result: C, transform : (T) -> R) : C {
if (this != null) {
result.add(transform(this))
}
@@ -151,31 +151,31 @@ inline fun <T, R, C: Collection<in R>> T?.mapTo(result: C, transform : (T) -> R)
}
/** Returns itself since it can't be reversed as it can contain at most one item */
inline fun <T> T?.reverse(): T? {
public inline fun <T> T?.reverse(): T? {
return this
}
/** Copies the collection into the given collection */
inline fun <T, C: Collection<T>> T?.to(result: C): C {
public inline fun <T, C: Collection<T>> T?.to(result: C): C {
if (this != null)
result.add(this)
return result
}
/** Converts the collection into a LinkedList */
inline fun <T> T?.toLinkedList(): LinkedList<T> = this.to(LinkedList<T>())
public inline fun <T> T?.toLinkedList(): LinkedList<T> = this.to(LinkedList<T>())
/** Converts the collection into a List */
inline fun <T> T?.toList(): List<T> = this.to(ArrayList<T>())
public inline fun <T> T?.toList(): List<T> = this.to(ArrayList<T>())
/** Converts the collection into a Set */
inline fun <T> T?.toSet(): Set<T> = this.to(HashSet<T>())
public inline fun <T> T?.toSet(): Set<T> = this.to(HashSet<T>())
/** Converts the collection into a SortedSet */
inline fun <T> T?.toSortedSet(): SortedSet<T> = this.to(TreeSet<T>())
public inline fun <T> T?.toSortedSet(): SortedSet<T> = this.to(TreeSet<T>())
/**
TODO figure out necessary variance/generics ninja stuff... :)
inline fun <in T> T?.toSortedList(transform: fun(T) : java.lang.Comparable<*>) : List<T> {
public inline fun <in T> T?.toSortedList(transform: fun(T) : java.lang.Comparable<*>) : List<T> {
val answer = this.toList()
answer.sort(transform)
return answer
@@ -10,11 +10,11 @@ import java.util.ArrayList
public class ChangeEvent(val source: Any, val name: String, val oldValue: Any?, val newValue: Any?) {
var propogationId: Any? = null
fun toString() = "ChangeEvent($name, $oldValue, $newValue)"
public fun toString() : String = "ChangeEvent($name, $oldValue, $newValue)"
}
public trait ChangeListener {
fun onPropertyChange(event: ChangeEvent): Unit
public fun onPropertyChange(event: ChangeEvent): Unit
}
/**
@@ -27,14 +27,14 @@ public abstract class ChangeSupport {
private var nameListeners: Map<String, List<ChangeListener>>? = null
fun addChangeListener(listener: ChangeListener) {
public fun addChangeListener(listener: ChangeListener) {
if (allListeners == null) {
allListeners = ArrayList<ChangeListener>()
}
allListeners?.add(listener)
}
fun addChangeListener(name: String, listener: ChangeListener) {
public fun addChangeListener(name: String, listener: ChangeListener) {
if (nameListeners == null) {
nameListeners = HashMap<String, List<ChangeListener>>()
}
@@ -68,12 +68,12 @@ public abstract class ChangeSupport {
}
}
fun onPropertyChange(fn: (ChangeEvent) -> Unit) {
public fun onPropertyChange(fn: (ChangeEvent) -> Unit) {
// TODO
//addChangeListener(DelegateChangeListener(fn))
}
fun onPropertyChange(name: String, fn: (ChangeEvent) -> Unit) {
public fun onPropertyChange(name: String, fn: (ChangeEvent) -> Unit) {
// TODO
//addChangeListener(name, DelegateChangeListener(fn))
}
@@ -89,7 +89,7 @@ see http://youtrack.jetbrains.com/issue/KT-1362
protected fun createChangeListener(fn: (ChangeEvent) -> Unit): ChangeListener {
return ChangeListener {
override fun onPropertyChange(event: ChangeEvent): Unit {
public override fun onPropertyChange(event: ChangeEvent): Unit {
fn(event)
}
}
@@ -99,7 +99,7 @@ see http://youtrack.jetbrains.com/issue/KT-1362
class DelegateChangeListener(val f: (ChangeEvent) -> Unit) : ChangeListener {
override fun onPropertyChange(event: ChangeEvent): Unit {
public override fun onPropertyChange(event: ChangeEvent): Unit {
f(event)
}
}
@@ -15,7 +15,7 @@ class StringTemplate(val values : Array<Any?>) {
/**
* Converts the template into a String
*/
fun toString() : String {
public fun toString() : String {
val out = StringBuilder()
forEach{ out.append(it) }
return out.toString() ?: ""
@@ -24,7 +24,7 @@ class StringTemplate(val values : Array<Any?>) {
/**
* Performs the given function on each value in the collection
*/
fun forEach(fn : (Any?) -> Unit) : Unit {
public fun forEach(fn : (Any?) -> Unit) : Unit {
for (v in values) {
fn(v)
}
@@ -38,7 +38,7 @@ class StringTemplate(val values : Array<Any?>) {
*
* See [[HtmlFormatter] and [[LocaleFormatter] respectively.
*/
fun StringTemplate.toString(formatter : Formatter) : String {
public fun StringTemplate.toString(formatter : Formatter) : String {
val buffer = StringBuilder()
append(buffer, formatter)
return buffer.toString() ?: ""
@@ -48,7 +48,7 @@ fun StringTemplate.toString(formatter : Formatter) : String {
* Appends the text representation of this string template to the given output
* using the supplied formatter
*/
fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit {
public fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit {
var constantText = true
this.forEach {
if (constantText) {
@@ -71,33 +71,33 @@ fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit {
* Converts this string template to internationalised text using the supplied
* [[LocaleFormatter]]
*/
fun StringTemplate.toLocale(formatter : LocaleFormatter = LocaleFormatter()) : String = toString(formatter)
public fun StringTemplate.toLocale(formatter : LocaleFormatter = LocaleFormatter()) : String = toString(formatter)
/**
* Converts this string template to HTML text
*/
fun StringTemplate.toHtml(formatter : HtmlFormatter = HtmlFormatter()) : String = toString(formatter)
public fun StringTemplate.toHtml(formatter : HtmlFormatter = HtmlFormatter()) : String = toString(formatter)
/**
* Represents a formatter and encoder of values in a [[StringTemplate]] which understands
* how to format values for a particular [[Locale]] such as with the [[LocaleFormatter]] or
* to escape particular characters in different output formats such as [[HtmlFormatter]
*/
trait Formatter {
fun format(buffer : Appendable, val value : Any?) : Unit
public trait Formatter {
public fun format(buffer : Appendable, val value : Any?) : Unit
}
/**
* Formats strings with no special encoding other than allowing the null text to be
* configured
*/
open class ToStringFormatter : Formatter {
public open class ToStringFormatter : Formatter {
var nullString : String = "null"
open fun toString() = "ToStringFormatter"
public open fun toString() : String = "ToStringFormatter"
override fun format(out : Appendable, value : Any?) {
public override fun format(out : Appendable, value : Any?) {
if (value == null) {
format(out, nullString)
} else if (value is StringTemplate) {
@@ -111,25 +111,25 @@ open class ToStringFormatter : Formatter {
* Formats the given string allowing derived classes to override this method
* to escape strings with special characters such as for HTML
*/
open fun format(out : Appendable, text : String) : Unit {
public open fun format(out : Appendable, text : String) : Unit {
out.append(text)
}
}
protected val defaultLocale : Locale = Locale.getDefault().sure()
public val defaultLocale : Locale = Locale.getDefault().sure()
/**
* Formats values using a given [[Locale]] for internationalisation
*/
open class LocaleFormatter(val locale : Locale = defaultLocale) : ToStringFormatter() {
public open class LocaleFormatter(val locale : Locale = defaultLocale) : ToStringFormatter() {
override fun toString() = "LocaleFormatter{$locale}"
public override fun toString() : String = "LocaleFormatter{$locale}"
public var numberFormat : NumberFormat = NumberFormat.getInstance(locale).sure()
public var dateFormat : DateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale).sure()
override fun format(out : Appendable, value : Any?) {
public override fun format(out : Appendable, value : Any?) {
if (value is Number) {
format(out, format(value))
} else if (value is Date) {
@@ -139,11 +139,11 @@ open class LocaleFormatter(val locale : Locale = defaultLocale) : ToStringFormat
}
}
fun format(number : Number) : String {
public fun format(number : Number) : String {
return numberFormat.format(number) ?: ""
}
fun format(date : Date) : String {
public fun format(date : Date) : String {
return dateFormat.format(date) ?: ""
}
}
@@ -151,11 +151,11 @@ open class LocaleFormatter(val locale : Locale = defaultLocale) : ToStringFormat
/**
* Formats values for HTML encoding, escaping special characters in HTML.
*/
class HtmlFormatter(locale : Locale = defaultLocale) : LocaleFormatter(locale) {
public class HtmlFormatter(locale : Locale = defaultLocale) : LocaleFormatter(locale) {
override fun toString() = "HtmlFormatter{$locale}"
public override fun toString() : String = "HtmlFormatter{$locale}"
override fun format(out : Appendable, value : Any?) {
public override fun format(out : Appendable, value : Any?) {
if (value is Node) {
out.append(value.toXmlString())
} else {
@@ -163,7 +163,7 @@ class HtmlFormatter(locale : Locale = defaultLocale) : LocaleFormatter(locale) {
}
}
override fun format(buffer : Appendable, text : String) : Unit {
public override fun format(buffer : Appendable, text : String) : Unit {
for (c in text) {
if (c == '<') buffer.append("&lt;")
else if (c == '>') buffer.append("&gt;")
+25 -25
View File
@@ -31,65 +31,65 @@ public var asserter: Asserter
}
/** Asserts that the given block returns true */
inline fun assertTrue(message: String, block: ()-> Boolean) {
public inline fun assertTrue(message: String, block: ()-> Boolean) {
val actual = block()
asserter.assertTrue(message, actual)
}
/** Asserts that the given block returns true */
inline fun assertTrue(block: ()-> Boolean) = assertTrue(block.toString(), block)
public inline fun assertTrue(block: ()-> Boolean) : Unit = assertTrue(block.toString(), block)
/** Asserts that the given block returns false */
inline fun assertNot(message: String, block: ()-> Boolean) {
public inline fun assertNot(message: String, block: ()-> Boolean) {
assertTrue(message){ !block() }
}
/** Asserts that the given block returns true */
inline fun assertNot(block: ()-> Boolean) = assertNot(block.toString(), block)
public inline fun assertNot(block: ()-> Boolean) : Unit = assertNot(block.toString(), block)
/** Asserts that the expression is true with an optional message */
inline fun assertTrue(actual: Boolean, message: String = "") {
public inline fun assertTrue(actual: Boolean, message: String = "") {
return assertEquals(true, actual, message)
}
/** Asserts that the expression is false with an optional message */
inline fun assertFalse(actual: Boolean, message: String = "") {
public inline fun assertFalse(actual: Boolean, message: String = "") {
return assertEquals(false, actual, message)
}
/** Asserts that the expected value is equal to the actual value, with an optional message */
inline fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
public inline fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
asserter.assertEquals(message, expected, actual)
}
/** Asserts that the expression is not null, with an optional message */
inline fun assertNotNull(actual: Any?, message: String = "") {
public inline fun assertNotNull(actual: Any?, message: String = "") {
asserter.assertNotNull(message, actual)
}
/** Asserts that the expression is null, with an optional message */
inline fun assertNull(actual: Any?, message: String = "") {
public inline fun assertNull(actual: Any?, message: String = "") {
asserter.assertNull(message, actual)
}
/** Marks a test as having failed if this point in the execution path is reached, with an optional message */
inline fun fail(message: String = "") {
public inline fun fail(message: String = "") {
asserter.fail(message)
}
/** Asserts that given function block returns the given expected value */
inline fun <T> expect(expected: T, block: ()-> T) {
public inline fun <T> expect(expected: T, block: ()-> T) {
expect(expected, block.toString(), block)
}
/** Asserts that given function block returns the given expected value and use the given message if it fails */
inline fun <T> expect(expected: T, message: String, block: ()-> T) {
public inline fun <T> expect(expected: T, message: String, block: ()-> T) {
val actual = block()
assertEquals(expected, actual, message)
}
/** Asserts that given function block fails by throwing an exception */
fun fails(block: ()-> Unit): Throwable? {
public fun fails(block: ()-> Unit): Throwable? {
try {
block()
asserter.fail("Expected an exception to be thrown")
@@ -101,7 +101,7 @@ fun fails(block: ()-> Unit): Throwable? {
}
/** Asserts that a block fails with a specific exception being thrown */
fun <T: Throwable> failsWith(block: ()-> Unit) {
public fun <T: Throwable> failsWith(block: ()-> Unit) {
try {
block()
asserter.fail("Expected an exception to be thrown")
@@ -115,7 +115,7 @@ fun <T: Throwable> failsWith(block: ()-> Unit) {
* Comments out a block of test code until it is implemented while keeping a link to the code
* to implement in your unit test output
*/
inline fun todo(block: ()-> Any) {
public inline fun todo(block: ()-> Any) {
println("TODO at " + (Exception() as java.lang.Throwable).getStackTrace()?.get(1) + " for " + block)
}
@@ -123,15 +123,15 @@ inline fun todo(block: ()-> Any) {
* A plugin for performing assertions which can reuse JUnit or TestNG
*/
trait Asserter {
fun assertTrue(message: String, actual: Boolean): Unit
public fun assertTrue(message: String, actual: Boolean): Unit
fun assertEquals(message: String, expected: Any?, actual: Any?): Unit
public fun assertEquals(message: String, expected: Any?, actual: Any?): Unit
fun assertNotNull(message: String, actual: Any?): Unit
public fun assertNotNull(message: String, actual: Any?): Unit
fun assertNull(message: String, actual: Any?): Unit
public fun assertNull(message: String, actual: Any?): Unit
fun fail(message: String): Unit
public fun fail(message: String): Unit
}
/**
@@ -139,30 +139,30 @@ trait Asserter {
*/
class DefaultAsserter() : Asserter {
override fun assertTrue(message : String, actual : Boolean) {
public override fun assertTrue(message : String, actual : Boolean) {
if (!actual) {
fail(message)
}
}
override fun assertEquals(message : String, expected : Any?, actual : Any?) {
public override fun assertEquals(message : String, expected : Any?, actual : Any?) {
if (expected != actual) {
fail("$message. Expected <$expected> actual <$actual>")
}
}
override fun assertNotNull(message : String, actual : Any?) {
public override fun assertNotNull(message : String, actual : Any?) {
if (actual == null) {
fail(message)
}
}
override fun assertNull(message : String, actual : Any?) {
public override fun assertNull(message : String, actual : Any?) {
if (actual != null) {
fail(message)
}
}
override fun fail(message : String) {
public override fun fail(message : String) {
// TODO work around compiler bug as it should never try call the private constructor
throw AssertionError(message as Object)
}
+2 -2
View File
@@ -3,7 +3,7 @@ package kotlin.util
/**
Executes current block and returns elapsed time in milliseconds
*/
fun measureTimeMillis(block: () -> Unit) : Long {
public fun measureTimeMillis(block: () -> Unit) : Long {
val start = System.currentTimeMillis()
block()
return System.currentTimeMillis() - start
@@ -12,7 +12,7 @@ fun measureTimeMillis(block: () -> Unit) : Long {
/**
Executes current block and returns elapsed time in nanoseconds
*/
fun measureTimeNano(block: () -> Unit) : Long {
public fun measureTimeNano(block: () -> Unit) : Long {
val start = System.nanoTime()
block()
return System.nanoTime() - start