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
+46 -46
View File
@@ -1,84 +1,84 @@
package jet package jet
fun Array<T>(val size : Int) : Array<T?> public fun Array<T>(public val size : Int) : Array<T?>
class Array<T>(val size : Int, init : (Int) -> T) { public class Array<T>(public val size : Int, init : (Int) -> T) {
fun get(index : Int) : T public fun get(index : Int) : T
fun set(index : Int, value : T) : Unit public fun set(index : Int, value : T) : Unit
fun iterator() : Iterator<T> public fun iterator() : Iterator<T>
val indices : IntRange public val indices : IntRange
} }
class ByteArray(val size : Int) { public class ByteArray(public val size : Int) {
fun get(index : Int) : Byte public fun get(index : Int) : Byte
fun set(index : Int, value : Byte) : Unit public fun set(index : Int, value : Byte) : Unit
fun iterator() : ByteIterator public fun iterator() : ByteIterator
val indices : IntRange public val indices : IntRange
} }
class ShortArray(val size : Int) { public class ShortArray(public val size : Int) {
fun get(index : Int) : Short public fun get(index : Int) : Short
fun set(index : Int, value : Short) : Unit public fun set(index : Int, value : Short) : Unit
fun iterator() : ShortIterator public fun iterator() : ShortIterator
val indices : IntRange public val indices : IntRange
} }
class IntArray(val size : Int) { public class IntArray(public val size : Int) {
fun get(index : Int) : Int public fun get(index : Int) : Int
fun set(index : Int, value : Int) : Unit public fun set(index : Int, value : Int) : Unit
fun iterator() : IntIterator public fun iterator() : IntIterator
val indices : IntRange public val indices : IntRange
} }
class LongArray(val size : Int) { public class LongArray(public val size : Int) {
fun get(index : Int) : Long public fun get(index : Int) : Long
fun set(index : Int, value : Long) : Unit public fun set(index : Int, value : Long) : Unit
fun iterator() : LongIterator public fun iterator() : LongIterator
val indices : IntRange public val indices : IntRange
} }
class FloatArray(val size : Int) { public class FloatArray(public val size : Int) {
fun get(index : Int) : Float public fun get(index : Int) : Float
fun set(index : Int, value : Float) : Unit public fun set(index : Int, value : Float) : Unit
fun iterator() : FloatIterator public fun iterator() : FloatIterator
val indices : IntRange public val indices : IntRange
} }
class DoubleArray(val size : Int) { public class DoubleArray(public val size : Int) {
fun get(index : Int) : Double public fun get(index : Int) : Double
fun set(index : Int, value : Double) : Unit public fun set(index : Int, value : Double) : Unit
fun iterator() : DoubleIterator public fun iterator() : DoubleIterator
val indices : IntRange public val indices : IntRange
} }
class CharArray(val size : Int) { public class CharArray(public val size : Int) {
fun get(index : Int) : Char public fun get(index : Int) : Char
fun set(index : Int, value : Char) : Unit public fun set(index : Int, value : Char) : Unit
fun iterator() : CharIterator public fun iterator() : CharIterator
val indices : IntRange public val indices : IntRange
} }
class BooleanArray(val size : Int) { public class BooleanArray(public val size : Int) {
fun get(index : Int) : Boolean public fun get(index : Int) : Boolean
fun set(index : Int, value : Boolean) : Unit public fun set(index : Int, value : Boolean) : Unit
fun iterator() : BooleanIterator public fun iterator() : BooleanIterator
val indices : IntRange public val indices : IntRange
} }
+18 -18
View File
@@ -1,37 +1,37 @@
package jet package jet
trait Iterable<out T> { public trait Iterable<out T> {
fun iterator() : Iterator<T> public fun iterator() : Iterator<T>
} }
trait ByteIterable : Iterable<Byte> { public trait ByteIterable : Iterable<Byte> {
override fun iterator() : ByteIterator public override fun iterator() : ByteIterator
} }
trait ShortIterable : Iterable<Short> { public trait ShortIterable : Iterable<Short> {
override fun iterator() : ShortIterator public override fun iterator() : ShortIterator
} }
trait IntIterable : Iterable<Int> { public trait IntIterable : Iterable<Int> {
override fun iterator() : IntIterator public override fun iterator() : IntIterator
} }
trait LongIterable : Iterable<Long> { public trait LongIterable : Iterable<Long> {
override fun iterator() : LongIterator public override fun iterator() : LongIterator
} }
trait FloatIterable : Iterable<Float> { public trait FloatIterable : Iterable<Float> {
override fun iterator() : FloatIterator public override fun iterator() : FloatIterator
} }
trait DoubleIterable : Iterable<Double> { public trait DoubleIterable : Iterable<Double> {
override fun iterator() : DoubleIterator public override fun iterator() : DoubleIterator
} }
trait BooleanIterable : Iterable<Boolean> { public trait BooleanIterable : Iterable<Boolean> {
override fun iterator() : BooleanIterator public override fun iterator() : BooleanIterator
} }
trait CharIterable : Iterable<Char> { public trait CharIterable : Iterable<Char> {
override fun iterator() : CharIterator public override fun iterator() : CharIterator
} }
+36 -36
View File
@@ -1,73 +1,73 @@
package jet package jet
trait Iterator<out T> { public trait Iterator<out T> {
fun next() : T public fun next() : T
val hasNext : Boolean public val hasNext : Boolean
} }
abstract open class ByteIterator() : Iterator<Byte> { public abstract class ByteIterator() : Iterator<Byte> {
abstract open fun nextByte() : Byte public abstract open fun nextByte() : Byte
override fun next() : Byte public override fun next() : Byte
} }
abstract open class ShortIterator() : Iterator<Short> { public abstract class ShortIterator() : Iterator<Short> {
abstract open fun nextShort() : Short public abstract open fun nextShort() : Short
override fun next() : Short public override fun next() : Short
} }
abstract open class CharIterator() : Iterator<Char> { public abstract class CharIterator() : Iterator<Char> {
abstract open fun nextChar() : Char public abstract open fun nextChar() : Char
override fun next() : Char public override fun next() : Char
} }
abstract open class IntIterator() : Iterator<Int> { public abstract class IntIterator() : Iterator<Int> {
abstract open fun nextInt() : Int public abstract open fun nextInt() : Int
override fun next() : Int public override fun next() : Int
} }
abstract open class LongIterator() : Iterator<Long> { public abstract class LongIterator() : Iterator<Long> {
abstract open fun nextLong() : Long public abstract open fun nextLong() : Long
override fun next() : Long public override fun next() : Long
} }
abstract open class FloatIterator() : Iterator<Float> { public abstract class FloatIterator() : Iterator<Float> {
abstract open fun nextFloat() : Float public abstract open fun nextFloat() : Float
override fun next() : Float public override fun next() : Float
} }
abstract open class DoubleIterator() : Iterator<Double> { public abstract class DoubleIterator() : Iterator<Double> {
abstract open fun nextDouble() : Double public abstract open fun nextDouble() : Double
override fun next() : Double public override fun next() : Double
} }
abstract open class BooleanIterator() : Iterator<Boolean> { abstract open public class BooleanIterator() : Iterator<Boolean> {
abstract open fun nextBoolean() : Boolean public abstract open fun nextBoolean() : Boolean
override fun next() : Boolean public override fun next() : Boolean
} }
fun <T> Iterator<T>.iterator() : Iterator<T> public fun <T> Iterator<T>.iterator() : Iterator<T>
fun ByteIterator.iterator() : ByteIterator public fun ByteIterator.iterator() : ByteIterator
fun ShortIterator.iterator() : ShortIterator public fun ShortIterator.iterator() : ShortIterator
fun CharIterator.iterator() : CharIterator public fun CharIterator.iterator() : CharIterator
fun IntIterator.iterator() : IntIterator public fun IntIterator.iterator() : IntIterator
fun BooleanIterator.iterator() : BooleanIterator public fun BooleanIterator.iterator() : BooleanIterator
fun DoubleIterator.iterator() : DoubleIterator public fun DoubleIterator.iterator() : DoubleIterator
fun FloatIterator.iterator() : FloatIterator public fun FloatIterator.iterator() : FloatIterator
fun LongIterator.iterator() : LongIterator public fun LongIterator.iterator() : LongIterator
+35 -35
View File
@@ -1,66 +1,66 @@
package jet package jet
annotation class volatile public annotation class volatile
annotation class atomic public annotation class atomic
fun <R> synchronized(lock: Any, block : () -> R) : R public fun <R> synchronized(lock: Any, block : () -> R) : R
fun Any?.identityEquals(other : Any?) : Boolean // = this === other public fun Any?.identityEquals(other : Any?) : Boolean // = this === other
// Can't write a body due to a bootstrapping problem (see JET-74) // Can't write a body due to a bootstrapping problem (see JET-74)
fun Any?.equals(other : Any?) : Boolean// = this === other public fun Any?.equals(other : Any?) : Boolean// = this === other
// Returns "null" for null // Returns "null" for null
fun Any?.toString() : String// = this === other public fun Any?.toString() : String// = this === other
fun <T : Any> T?.sure() : T public fun <T : Any> T?.sure() : T
fun String?.plus(other: Any?) : String public fun String?.plus(other: Any?) : String
trait Comparable<in T> { public trait Comparable<in T> {
fun compareTo(other : T) : Int public fun compareTo(other : T) : Int
} }
trait Hashable { public trait Hashable {
fun hashCode() : Int public fun hashCode() : Int
fun equals(other : Any?) : Boolean public fun equals(other : Any?) : Boolean
} }
class Boolean : Comparable<Boolean> { public class Boolean : Comparable<Boolean> {
fun not() : Boolean public fun not() : Boolean
fun and(other : Boolean) : Boolean public fun and(other : Boolean) : Boolean
fun or(other : Boolean) : Boolean public fun or(other : Boolean) : Boolean
fun xor(other : Boolean) : Boolean public fun xor(other : Boolean) : Boolean
fun equals(other : Any?) : Boolean public fun equals(other : Any?) : Boolean
override fun compareTo(that : Boolean) : Int public override fun compareTo(that : Boolean) : Int
} }
trait CharSequence { public trait CharSequence {
fun get(index : Int) : Char public fun get(index : Int) : Char
val length : Int public val length : Int
fun toString() : String public fun toString() : String
} }
class String() : Comparable<String>, CharSequence { public class String() : Comparable<String>, CharSequence {
fun plus(other : Any?) : String public fun plus(other : Any?) : String
fun equals(other : Any?) : Boolean public fun equals(other : Any?) : Boolean
override fun compareTo(that : String) : Int public override fun compareTo(that : String) : Int
override fun get(index : Int) : Char public override fun get(index : Int) : Char
override fun toString() : String public override fun toString() : String
override val length: Int public override val length: Int
} }
open class Throwable(message : String? = null, cause: Throwable? = null) { public open class Throwable(message : String? = null, cause: Throwable? = null) {
fun getMessage() : String? public fun getMessage() : String?
fun getCause() : Throwable? public fun getCause() : Throwable?
fun printStackTrace() : Unit public fun printStackTrace() : Unit
} }
File diff suppressed because it is too large Load Diff
+54 -54
View File
@@ -1,109 +1,109 @@
package jet package jet
trait Range<in T : Comparable<T>> { public trait Range<in T : Comparable<T>> {
fun contains(item : T) : Boolean public fun contains(item : T) : Boolean
} }
class IntRange(val start : Int, val size : Int) : Range<Int>, IntIterable { public class IntRange(public val start : Int, public val size : Int) : Range<Int>, IntIterable {
override fun iterator () : IntIterator public override fun iterator () : IntIterator
override fun contains (elem: Int) : Boolean public override fun contains (elem: Int) : Boolean
val end : Int public val end : Int
val iteratorStart : Int public val iteratorStart : Int
fun minus() : IntRange public fun minus() : IntRange
fun step(step: Int) : IntIterator public fun step(step: Int) : IntIterator
val isReversed : Boolean public val isReversed : Boolean
} }
class LongRange(val start : Long, val size : Long) : Range<Long>, LongIterable { public class LongRange(public val start : Long, public val size : Long) : Range<Long>, LongIterable {
override fun iterator () : LongIterator public override fun iterator () : LongIterator
override fun contains (elem: Long) : Boolean public override fun contains (elem: Long) : Boolean
val iteratorStart : Long public val iteratorStart : Long
val end : Long public val end : Long
fun minus() : LongRange public fun minus() : LongRange
fun step(step: Long) : LongIterator public fun step(step: Long) : LongIterator
val isReversed : Boolean public val isReversed : Boolean
} }
class ByteRange(val start : Byte, val size : Int) : Range<Byte>, ByteIterable { public class ByteRange(public val start : Byte, public val size : Int) : Range<Byte>, ByteIterable {
override fun iterator () : ByteIterator public override fun iterator () : ByteIterator
override fun contains (elem: Byte) : Boolean public override fun contains (elem: Byte) : Boolean
val end : Byte public val end : Byte
val iteratorStart : Byte public val iteratorStart : Byte
fun minus() : ByteRange public fun minus() : ByteRange
fun step(step: Int) : ByteIterator public fun step(step: Int) : ByteIterator
val isReversed : Boolean public val isReversed : Boolean
} }
class ShortRange(val start : Short, val size : Int) : Range<Short>, ShortIterable { public class ShortRange(public val start : Short, public val size : Int) : Range<Short>, ShortIterable {
override fun iterator () : ShortIterator public override fun iterator () : ShortIterator
override fun contains (elem: Short) : Boolean public override fun contains (elem: Short) : Boolean
val iteratorStart : Short public val iteratorStart : Short
val end : Short public val end : Short
fun minus() : ShortRange public fun minus() : ShortRange
fun step(step: Int) : ShortIterator public fun step(step: Int) : ShortIterator
val isReversed : Boolean public val isReversed : Boolean
} }
class CharRange(val start : Char, val size : Int) : Range<Char>, CharIterable { public class CharRange(public val start : Char, public val size : Int) : Range<Char>, CharIterable {
override fun iterator () : CharIterator public override fun iterator () : CharIterator
override fun contains (elem: Char) : Boolean public override fun contains (elem: Char) : Boolean
val iteratorStart : Char public val iteratorStart : Char
val end : Char public val end : Char
fun minus() : CharRange public fun minus() : CharRange
fun step(step: Int) : CharIterator public fun step(step: Int) : CharIterator
val isReversed : Boolean public val isReversed : Boolean
} }
class FloatRange(val start : Float, val size : Float) : Range<Float> { public class FloatRange(public val start : Float, public val size : Float) : Range<Float> {
override fun contains (elem: Float) : Boolean public override fun contains (elem: Float) : Boolean
val end : Float public val end : Float
fun minus() : FloatRange public fun minus() : FloatRange
fun step(step: Float) : FloatIterator public fun step(step: Float) : FloatIterator
val isReversed : Boolean public val isReversed : Boolean
} }
class DoubleRange(val start : Double, val size : Double) : Range<Double> { public class DoubleRange(public val start : Double, public val size : Double) : Range<Double> {
override fun contains (elem: Double) : Boolean public override fun contains (elem: Double) : Boolean
val end : Double public val end : Double
fun minus() : DoubleRange public fun minus() : DoubleRange
fun step(step: Double) : DoubleIterator public fun step(step: Double) : DoubleIterator
val isReversed : Boolean public val isReversed : Boolean
} }
@@ -4,7 +4,7 @@ BLACK
RED RED
YELLOW YELLOW
BLUE BLUE
override public fun run() : Unit { public override fun run() : Unit {
System.out?.println("name()=" + name() + ", toString()=" + toString()) System.out?.println("name()=" + name() + ", toString()=" + toString())
} }
public fun name() : String { return "" } public fun name() : String { return "" }
@@ -1,15 +1,15 @@
package test package test
open class Test() : Base() { open class Test() : Base() {
override public fun hashCode() : Int { public override fun hashCode() : Int {
return super.hashCode() return super.hashCode()
} }
override public fun equals(o : Any?) : Boolean { public override fun equals(o : Any?) : Boolean {
return super.equals(o) return super.equals(o)
} }
override protected fun clone() : Any? { override protected fun clone() : Any? {
return super.clone() return super.clone()
} }
override public fun toString() : String? { public override fun toString() : String? {
return super.toString() return super.toString()
} }
override protected fun finalize() : Unit { override protected fun finalize() : Unit {
+3 -3
View File
@@ -11,13 +11,13 @@ return getJavaClass<Base>.getName() + '@' + Integer.toHexString(hashCode())
} }
} }
open class Child() : Base() { open class Child() : Base() {
override public fun hashCode() : Int { public override fun hashCode() : Int {
return super.hashCode() return super.hashCode()
} }
override public fun equals(o : Any?) : Boolean { public override fun equals(o : Any?) : Boolean {
return super.equals(o) return super.equals(o)
} }
override public fun toString() : String? { public override fun toString() : String? {
return super.toString() return super.toString()
} }
} }
+1 -1
View File
@@ -2,7 +2,7 @@ package com.voltvoodoo.saplo4j.model
import java.io.Serializable import java.io.Serializable
public open class Language(code : String?) : Serializable { public open class Language(code : String?) : Serializable {
protected var code : String? = null protected var code : String? = null
override public fun toString() : String? { public override fun toString() : String? {
return this.code return this.code
} }
{ {
@@ -1,7 +1,7 @@
package demo package demo
import java.util.Iterator import java.util.Iterator
open class Test() : java.lang.Iterable<String?> { open class Test() : java.lang.Iterable<String?> {
override public fun iterator() : java.util.Iterator<String?>? { public override fun iterator() : java.util.Iterator<String?>? {
return null return null
} }
open public fun push(i : java.util.Iterator<String?>?) : java.util.Iterator<String?>? { open public fun push(i : java.util.Iterator<String?>?) : java.util.Iterator<String?>? {
@@ -10,7 +10,7 @@ return j
} }
} }
open class FullTest() : java.lang.Iterable<String?> { open class FullTest() : java.lang.Iterable<String?> {
override public fun iterator() : java.util.Iterator<String?>? { public override fun iterator() : java.util.Iterator<String?>? {
return null return null
} }
open public fun push(i : java.util.Iterator<String?>?) : java.util.Iterator<String?>? { open public fun push(i : java.util.Iterator<String?>?) : java.util.Iterator<String?>? {
@@ -1,5 +1,5 @@
object : Runnable() { object : Runnable() {
override public fun run() : Unit { public override fun run() : Unit {
System.out?.println("Run") System.out?.println("Run")
} }
} }
@@ -6,12 +6,12 @@ open public fun windowClosing() : Unit {
public class Client() : Frame() { public class Client() : Frame() {
{ {
var a : WindowAdapter? = object : WindowAdapter() { var a : WindowAdapter? = object : WindowAdapter() {
override public fun windowClosing() : Unit { public override fun windowClosing() : Unit {
} }
} }
addWindowListener(a) addWindowListener(a)
addWindowListener(object : WindowAdapter() { addWindowListener(object : WindowAdapter() {
override public fun windowClosing() : Unit { public override fun windowClosing() : Unit {
} }
}) })
} }
+15 -15
View File
@@ -1,17 +1,17 @@
package java.util package java.util
abstract public open class AbstractCollection<erased E> protected () : java.lang.Object(), java.util.Collection<E> { public abstract class AbstractCollection<erased E> protected () : java.lang.Object(), java.util.Collection<E> {
abstract override public fun iterator() : java.util.Iterator<E> public abstract override fun iterator() : java.util.Iterator<E>
abstract override public fun size() : Int public abstract override fun size() : Int
override public fun isEmpty() : Boolean {} public override fun isEmpty() : Boolean {}
override public fun contains(o : Any?) : Boolean {} public override fun contains(o : Any?) : Boolean {}
override public fun toArray() : Array<Any?> {} public override fun toArray() : Array<Any?> {}
override public fun toArray<erased T>(a : Array<out T>) : Array<T> {} public override fun toArray<erased T>(a : Array<out T>) : Array<T> {}
override public fun add(e : E) : Boolean {} public override fun add(e : E) : Boolean {}
override public fun remove(o : Any?) : Boolean {} public override fun remove(o : Any?) : Boolean {}
override public fun containsAll(c : java.util.Collection<*>) : Boolean {} public override fun containsAll(c : java.util.Collection<*>) : Boolean {}
override public fun addAll(c : java.util.Collection<out E>) : Boolean {} public override fun addAll(c : java.util.Collection<out E>) : Boolean {}
override public fun removeAll(c : java.util.Collection<*>) : Boolean {} public override fun removeAll(c : java.util.Collection<*>) : Boolean {}
override public fun retainAll(c : java.util.Collection<*>) : Boolean {} public override fun retainAll(c : java.util.Collection<*>) : Boolean {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
//override public fun toString() : java.lang.String {} //public override fun toString() : java.lang.String {}
} }
+16 -16
View File
@@ -1,20 +1,20 @@
package java.util package java.util
abstract public open class AbstractList<erased E> protected () : java.util.AbstractCollection<E>(), java.util.List<E> { public abstract class AbstractList<erased E> protected () : java.util.AbstractCollection<E>(), java.util.List<E> {
override public fun add(e : E) : Boolean {} public override fun add(e : E) : Boolean {}
abstract override public fun get(index : Int) : E public abstract override fun get(index : Int) : E
override public fun set(index : Int, element : E) : E {} public override fun set(index : Int, element : E) : E {}
override public fun add(index : Int, element : E) : Unit {} public override fun add(index : Int, element : E) : Unit {}
override public fun remove(index : Int) : E {} public override fun remove(index : Int) : E {}
override public fun indexOf(o : Any?) : Int {} public override fun indexOf(o : Any?) : Int {}
override public fun lastIndexOf(o : Any?) : Int {} public override fun lastIndexOf(o : Any?) : Int {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
override public fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {} public override fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {}
override public fun iterator() : java.util.Iterator<E> {} public override fun iterator() : java.util.Iterator<E> {}
override public fun listIterator() : java.util.ListIterator<E> {} public override fun listIterator() : java.util.ListIterator<E> {}
override public fun listIterator(index : Int) : java.util.ListIterator<E> {} public override fun listIterator(index : Int) : java.util.ListIterator<E> {}
override public fun subList(fromIndex : Int, toIndex : Int) : java.util.List<E> {} public override fun subList(fromIndex : Int, toIndex : Int) : java.util.List<E> {}
// override public fun equals(o : Any?) : Boolean // public override fun equals(o : Any?) : Boolean
// override public fun hashCode() : Int // public override fun hashCode() : Int
open protected fun removeRange(fromIndex : Int, toIndex : Int) : Unit {} open protected fun removeRange(fromIndex : Int, toIndex : Int) : Unit {}
protected var modCount : Int = 0 protected var modCount : Int = 0
} }
+16 -16
View File
@@ -2,20 +2,20 @@ package java.util
import java.util.Map.Entry import java.util.Map.Entry
abstract public open class AbstractMap<erased K, erased V> protected () : java.lang.Object(), java.util.Map<K, V> { public abstract class AbstractMap<erased K, erased V> protected () : java.lang.Object(), java.util.Map<K, V> {
override public fun size() : Int {} public override fun size() : Int {}
override public fun isEmpty() : Boolean {} public override fun isEmpty() : Boolean {}
override public fun containsValue(value : Any?) : Boolean {} public override fun containsValue(value : Any?) : Boolean {}
override public fun containsKey(key : Any?) : Boolean {} public override fun containsKey(key : Any?) : Boolean {}
override public fun get(key : Any?) : V? {} public override fun get(key : Any?) : V? {}
override public fun put(key : K, value : V) : V? {} public override fun put(key : K, value : V) : V? {}
override public fun remove(key : Any?) : V? {} public override fun remove(key : Any?) : V? {}
override public fun putAll(m : java.util.Map<out K, out V>) : Unit {} public override fun putAll(m : java.util.Map<out K, out V>) : Unit {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
override public fun keySet() : java.util.Set<K> {} public override fun keySet() : java.util.Set<K> {}
override public fun values() : java.util.Collection<V> {} public override fun values() : java.util.Collection<V> {}
abstract override public fun entrySet() : java.util.Set<Entry<K, V>> public abstract override fun entrySet() : java.util.Set<Entry<K, V>>
//override public fun equals(o : Any?) : Boolean //public override fun equals(o : Any?) : Boolean
//override public fun hashCode() : Int //public override fun hashCode() : Int
//override public fun toString() : java.lang.String? //public override fun toString() : java.lang.String?
} }
@@ -1,10 +1,10 @@
package java.util package java.util
abstract public open class AbstractSequentialList<erased E> protected () : java.util.AbstractList<E>() { public abstract class AbstractSequentialList<erased E> protected () : java.util.AbstractList<E>() {
override public fun get(index : Int) : E {} public override fun get(index : Int) : E {}
override public fun set(index : Int, element : E) : E {} public override fun set(index : Int, element : E) : E {}
override public fun add(index : Int, element : E) : Unit {} public override fun add(index : Int, element : E) : Unit {}
override public fun remove(index : Int) : E {} public override fun remove(index : Int) : E {}
override public fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {} public override fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {}
override public fun iterator() : java.util.Iterator<E> {} public override fun iterator() : java.util.Iterator<E> {}
abstract override public fun listIterator(index : Int) : java.util.ListIterator<E> {} public abstract override fun listIterator(index : Int) : java.util.ListIterator<E> {}
} }
+4 -4
View File
@@ -1,6 +1,6 @@
package java.util package java.util
abstract public open class AbstractSet<erased E> protected () : java.util.AbstractCollection<E>(), java.util.Set<E> { public abstract class AbstractSet<erased E> protected () : java.util.AbstractCollection<E>(), java.util.Set<E> {
// override public fun equals(o : Any?) : Boolean // public override fun equals(o : Any?) : Boolean
// override public fun hashCode() : Int // public override fun hashCode() : Int
override public fun removeAll(c : java.util.Collection<*>) : Boolean {} public override fun removeAll(c : java.util.Collection<*>) : Boolean {}
} }
+17 -17
View File
@@ -8,23 +8,23 @@ public open class ArrayList<erased E>(c : java.util.Collection<out E>) : java.ut
public this(initialCapacity : Int) {} public this(initialCapacity : Int) {}
open public fun trimToSize() : Unit {} open public fun trimToSize() : Unit {}
open public fun ensureCapacity(minCapacity : Int) : Unit {} open public fun ensureCapacity(minCapacity : Int) : Unit {}
override public fun size() : Int {} public override fun size() : Int {}
override public fun isEmpty() : Boolean {} public override fun isEmpty() : Boolean {}
override public fun contains(o : Any?) : Boolean {} public override fun contains(o : Any?) : Boolean {}
override public fun indexOf(o : Any?) : Int {} public override fun indexOf(o : Any?) : Int {}
override public fun lastIndexOf(o : Any?) : Int {} public override fun lastIndexOf(o : Any?) : Int {}
override public fun clone() : java.lang.Object {} public override fun clone() : java.lang.Object {}
override public fun toArray() : Array<Any?> {} public override fun toArray() : Array<Any?> {}
override public fun toArray<erased T>(a : Array<out T>) : Array<T> {} public override fun toArray<erased T>(a : Array<out T>) : Array<T> {}
override public fun get(index : Int) : E {} public override fun get(index : Int) : E {}
override public fun set(index : Int, element : E) : E {} public override fun set(index : Int, element : E) : E {}
override public fun add(e : E) : Boolean {} public override fun add(e : E) : Boolean {}
override public fun add(index : Int, element : E) : Unit {} public override fun add(index : Int, element : E) : Unit {}
override public fun remove(index : Int) : E {} public override fun remove(index : Int) : E {}
override public fun remove(o : Any?) : Boolean {} public override fun remove(o : Any?) : Boolean {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
override public fun addAll(c : java.util.Collection<out E>) : Boolean {} public override fun addAll(c : java.util.Collection<out E>) : Boolean {}
override public fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {} public override fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {}
override protected fun removeRange(fromIndex : Int, toIndex : Int) : Unit {} override protected fun removeRange(fromIndex : Int, toIndex : Int) : Unit {}
// class object { // class object {
// open public fun init<E>() : ArrayList<E> { // open public fun init<E>() : ArrayList<E> {
+1 -1
View File
@@ -24,7 +24,7 @@ public trait Deque<erased E> : java.util.Queue<E> {
open fun pop() : E open fun pop() : E
override fun remove(o : Any?) : Boolean override fun remove(o : Any?) : Boolean
override fun contains(o : Any?) : Boolean override fun contains(o : Any?) : Boolean
override public fun size() : Int public override fun size() : Int
override fun iterator() : java.util.Iterator<E> override fun iterator() : java.util.Iterator<E>
open fun descendingIterator() : java.util.Iterator<E> open fun descendingIterator() : java.util.Iterator<E>
} }
+13 -13
View File
@@ -8,17 +8,17 @@ public open class HashMap<erased K, erased V>(m : java.util.Map<out K, out V>) :
public this() {} public this() {}
public this(initialCapacity : Int) {} public this(initialCapacity : Int) {}
public this(initialCapacity : Int, loadFactor : Float) {} public this(initialCapacity : Int, loadFactor : Float) {}
override public fun size() : Int {} public override fun size() : Int {}
override public fun isEmpty() : Boolean {} public override fun isEmpty() : Boolean {}
override public fun get(key : Any?) : V? {} public override fun get(key : Any?) : V? {}
override public fun containsKey(key : Any?) : Boolean {} public override fun containsKey(key : Any?) : Boolean {}
override public fun put(key : K, value : V) : V? {} public override fun put(key : K, value : V) : V? {}
override public fun putAll(m : java.util.Map<out K, out V>) : Unit {} public override fun putAll(m : java.util.Map<out K, out V>) : Unit {}
override public fun remove(key : Any?) : V? {} public override fun remove(key : Any?) : V? {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
override public fun containsValue(value : Any?) : Boolean {} public override fun containsValue(value : Any?) : Boolean {}
override public fun clone() : Any? {} public override fun clone() : Any? {}
override public fun keySet() : java.util.Set<K> {} public override fun keySet() : java.util.Set<K> {}
override public fun values() : java.util.Collection<V> {} public override fun values() : java.util.Collection<V> {}
override public fun entrySet() : java.util.Set<Entry<K, V>> {} public override fun entrySet() : java.util.Set<Entry<K, V>> {}
} }
+8 -8
View File
@@ -6,14 +6,14 @@ public open class HashSet<erased E>(c : java.util.Collection<out E>) : java.util
public this() {} public this() {}
public this(initialCapacity : Int) {} public this(initialCapacity : Int) {}
public this(initialCapacity : Int, loadFactor : Float) {} public this(initialCapacity : Int, loadFactor : Float) {}
override public fun iterator() : java.util.Iterator<E> {} public override fun iterator() : java.util.Iterator<E> {}
override public fun size() : Int {} public override fun size() : Int {}
override public fun isEmpty() : Boolean {} public override fun isEmpty() : Boolean {}
override public fun contains(o : Any?) : Boolean {} public override fun contains(o : Any?) : Boolean {}
override public fun add(e : E) : Boolean {} public override fun add(e : E) : Boolean {}
override public fun remove(o : Any?) : Boolean {} public override fun remove(o : Any?) : Boolean {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
override public fun clone() : Any? {} public override fun clone() : Any? {}
//class object { //class object {
//open public fun init<E>() : HashSet<E> { //open public fun init<E>() : HashSet<E> {
//val __ = HashSet(0, null, null) //val __ = HashSet(0, null, null)
+3 -3
View File
@@ -7,9 +7,9 @@ public open class LinkedHashMap<erased K, erased V>(m : java.util.Map<out K, out
public this(initialCapacity : Int) {} public this(initialCapacity : Int) {}
public this() {} public this() {}
override public fun containsValue(value : Any?) : Boolean {} public override fun containsValue(value : Any?) : Boolean {}
override public fun get(key : Any?) : V? {} public override fun get(key : Any?) : V? {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
open protected fun removeEldestEntry(eldest : Entry<K, V>) : Boolean {} open protected fun removeEldestEntry(eldest : Entry<K, V>) : Boolean {}
//class object { //class object {
//open public fun init<K, V>(initialCapacity : Int, loadFactor : Float) : LinkedHashMap<K, V> { //open public fun init<K, V>(initialCapacity : Int, loadFactor : Float) : LinkedHashMap<K, V> {
+39 -39
View File
@@ -6,45 +6,45 @@ public open class LinkedList<erased E>(c : java.util.Collection<out E>) : java.u
java.io.Serializable { java.io.Serializable {
public this() {} public this() {}
override public fun getFirst() : E {} public override fun getFirst() : E {}
override public fun getLast() : E {} public override fun getLast() : E {}
override public fun removeFirst() : E {} public override fun removeFirst() : E {}
override public fun removeLast() : E {} public override fun removeLast() : E {}
override public fun addFirst(e : E) : Unit {} public override fun addFirst(e : E) : Unit {}
override public fun addLast(e : E) : Unit {} public override fun addLast(e : E) : Unit {}
override public fun contains(o : Any?) : Boolean {} public override fun contains(o : Any?) : Boolean {}
override public fun size() : Int {} public override fun size() : Int {}
override public fun add(e : E) : Boolean {} public override fun add(e : E) : Boolean {}
override public fun remove(o : Any?) : Boolean {} public override fun remove(o : Any?) : Boolean {}
override public fun addAll(c : java.util.Collection<out E>) : Boolean {} public override fun addAll(c : java.util.Collection<out E>) : Boolean {}
override public fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {} public override fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean {}
override public fun clear() : Unit {} public override fun clear() : Unit {}
override public fun get(index : Int) : E {} public override fun get(index : Int) : E {}
override public fun set(index : Int, element : E) : E {} public override fun set(index : Int, element : E) : E {}
override public fun add(index : Int, element : E) : Unit {} public override fun add(index : Int, element : E) : Unit {}
override public fun remove(index : Int) : E {} public override fun remove(index : Int) : E {}
override public fun indexOf(o : Any?) : Int {} public override fun indexOf(o : Any?) : Int {}
override public fun lastIndexOf(o : Any?) : Int {} public override fun lastIndexOf(o : Any?) : Int {}
override public fun peek() : E? {} public override fun peek() : E? {}
override public fun element() : E {} public override fun element() : E {}
override public fun poll() : E? {} public override fun poll() : E? {}
override public fun remove() : E {} public override fun remove() : E {}
override public fun offer(e : E) : Boolean {} public override fun offer(e : E) : Boolean {}
override public fun offerFirst(e : E) : Boolean {} public override fun offerFirst(e : E) : Boolean {}
override public fun offerLast(e : E) : Boolean {} public override fun offerLast(e : E) : Boolean {}
override public fun peekFirst() : E? {} public override fun peekFirst() : E? {}
override public fun peekLast() : E? {} public override fun peekLast() : E? {}
override public fun pollFirst() : E? {} public override fun pollFirst() : E? {}
override public fun pollLast() : E? {} public override fun pollLast() : E? {}
override public fun push(e : E) : Unit {} public override fun push(e : E) : Unit {}
override public fun pop() : E {} public override fun pop() : E {}
override public fun removeFirstOccurrence(o : Any?) : Boolean {} public override fun removeFirstOccurrence(o : Any?) : Boolean {}
override public fun removeLastOccurrence(o : Any?) : Boolean {} public override fun removeLastOccurrence(o : Any?) : Boolean {}
override public fun listIterator(index : Int) : java.util.ListIterator<E> {} public override fun listIterator(index : Int) : java.util.ListIterator<E> {}
override public fun descendingIterator() : java.util.Iterator<E> {} public override fun descendingIterator() : java.util.Iterator<E> {}
override public fun clone() : Any? {} public override fun clone() : Any? {}
override public fun toArray() : Array<Any?> {} public override fun toArray() : Array<Any?> {}
override public fun toArray<erased T>(a : Array<out T>) : Array<T> {} public override fun toArray<erased T>(a : Array<out T>) : Array<T> {}
//class object { //class object {
//open public fun init<E>(c : java.util.Collection<out E?>?) : LinkedList<E> { //open public fun init<E>(c : java.util.Collection<out E?>?) : LinkedList<E> {
//return __ //return __
+47 -47
View File
@@ -29,23 +29,23 @@ val Collections = object {
library library
public open class ArrayList<erased E>() : java.util.List<E> { public open class ArrayList<erased E>() : java.util.List<E> {
override public fun size() : Int = js.noImpl public override fun size() : Int = js.noImpl
override public fun isEmpty() : Boolean = js.noImpl public override fun isEmpty() : Boolean = js.noImpl
override public fun contains(o : Any?) : Boolean = js.noImpl public override fun contains(o : Any?) : Boolean = js.noImpl
override public fun iterator() : Iterator<E> = js.noImpl public override fun iterator() : Iterator<E> = js.noImpl
// override public fun indexOf(o : Any?) : Int = js.noImpl // public override fun indexOf(o : Any?) : Int = js.noImpl
// override public fun lastIndexOf(o : Any?) : Int = js.noImpl // public override fun lastIndexOf(o : Any?) : Int = js.noImpl
// override public fun toArray() : Array<Any?> = js.noImpl // public override fun toArray() : Array<Any?> = js.noImpl
// override public fun toArray<erased T>(a : Array<out T>) : Array<T> = js.noImpl // public override fun toArray<erased T>(a : Array<out T>) : Array<T> = js.noImpl
override public fun get(index : Int) : E = js.noImpl public override fun get(index : Int) : E = js.noImpl
override public fun set(index : Int, element : E) : E = js.noImpl public override fun set(index : Int, element : E) : E = js.noImpl
override public fun add(e : E) : Boolean = js.noImpl public override fun add(e : E) : Boolean = js.noImpl
override public fun add(index : Int, element : E) : Unit = js.noImpl public override fun add(index : Int, element : E) : Unit = js.noImpl
override public fun remove(index : Int) : E = js.noImpl public override fun remove(index : Int) : E = js.noImpl
override public fun remove(o : Any?) : Boolean = js.noImpl public override fun remove(o : Any?) : Boolean = js.noImpl
override public fun clear() : Unit = js.noImpl public override fun clear() : Unit = js.noImpl
override public fun addAll(c : java.util.Collection<out E>) : Boolean = js.noImpl public override fun addAll(c : java.util.Collection<out E>) : Boolean = js.noImpl
// override public fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean = js.noImpl // public override fun addAll(index : Int, c : java.util.Collection<out E>) : Boolean = js.noImpl
} }
library library
@@ -109,13 +109,13 @@ public trait Set<erased E> : Collection<E> {
library library
public open class HashSet<erased E>() : java.util.Set<E> { public open class HashSet<erased E>() : java.util.Set<E> {
override public fun iterator() : java.util.Iterator<E> = js.noImpl public override fun iterator() : java.util.Iterator<E> = js.noImpl
override public fun size() : Int = js.noImpl public override fun size() : Int = js.noImpl
override public fun isEmpty() : Boolean = js.noImpl public override fun isEmpty() : Boolean = js.noImpl
override public fun contains(o : Any?) : Boolean = js.noImpl public override fun contains(o : Any?) : Boolean = js.noImpl
override public fun add(e : E) : Boolean = js.noImpl public override fun add(e : E) : Boolean = js.noImpl
override public fun remove(o : Any?) : Boolean = js.noImpl public override fun remove(o : Any?) : Boolean = js.noImpl
override public fun clear() : Unit = js.noImpl public override fun clear() : Unit = js.noImpl
override fun addAll(c : java.util.Collection<out E>) : Boolean = js.noImpl override fun addAll(c : java.util.Collection<out E>) : Boolean = js.noImpl
} }
@@ -136,33 +136,33 @@ public trait Map<erased K, erased V> {
library library
public open class HashMap<erased K, erased V>() : java.util.Map<K, V> { public open class HashMap<erased K, erased V>() : java.util.Map<K, V> {
override public fun size() : Int = js.noImpl public override fun size() : Int = js.noImpl
override public fun isEmpty() : Boolean = js.noImpl public override fun isEmpty() : Boolean = js.noImpl
override public fun get(key : Any?) : V = js.noImpl public override fun get(key : Any?) : V = js.noImpl
override public fun containsKey(key : Any?) : Boolean = js.noImpl public override fun containsKey(key : Any?) : Boolean = js.noImpl
override public fun put(key : K, value : V) : V = js.noImpl public override fun put(key : K, value : V) : V = js.noImpl
override public fun putAll(m : java.util.Map<out K, out V>) : Unit = js.noImpl public override fun putAll(m : java.util.Map<out K, out V>) : Unit = js.noImpl
override public fun remove(key : Any?) : V? = js.noImpl public override fun remove(key : Any?) : V? = js.noImpl
override public fun clear() : Unit = js.noImpl public override fun clear() : Unit = js.noImpl
override public fun containsValue(value : Any?) : Boolean = js.noImpl public override fun containsValue(value : Any?) : Boolean = js.noImpl
override public fun keySet() : java.util.Set<K> = js.noImpl public override fun keySet() : java.util.Set<K> = js.noImpl
override public fun values() : java.util.Collection<V> = js.noImpl public override fun values() : java.util.Collection<V> = js.noImpl
} }
library library
public open class LinkedList<erased E>() : List<E> { public open class LinkedList<erased E>() : List<E> {
override public fun iterator() : java.util.Iterator<E> = js.noImpl public override fun iterator() : java.util.Iterator<E> = js.noImpl
override public fun isEmpty() : Boolean = js.noImpl public override fun isEmpty() : Boolean = js.noImpl
override public fun contains(o : Any?) : Boolean = js.noImpl public override fun contains(o : Any?) : Boolean = js.noImpl
override public fun size() : Int = js.noImpl public override fun size() : Int = js.noImpl
override public fun add(e : E) : Boolean = js.noImpl public override fun add(e : E) : Boolean = js.noImpl
override public fun remove(o : Any?) : Boolean = js.noImpl public override fun remove(o : Any?) : Boolean = js.noImpl
override public fun addAll(c : java.util.Collection<out E>) : Boolean = js.noImpl public override fun addAll(c : java.util.Collection<out E>) : Boolean = js.noImpl
override public fun clear() : Unit = js.noImpl public override fun clear() : Unit = js.noImpl
override public fun get(index : Int) : E = js.noImpl public override fun get(index : Int) : E = js.noImpl
override public fun set(index : Int, element : E) : E = js.noImpl public override fun set(index : Int, element : E) : E = js.noImpl
override public fun add(index : Int, element : E) : Unit = js.noImpl public override fun add(index : Int, element : E) : Unit = js.noImpl
override public fun remove(index : Int) : E = js.noImpl public override fun remove(index : Int) : E = js.noImpl
public fun poll() : E? = js.noImpl public fun poll() : E? = js.noImpl
public fun peek() : E? = js.noImpl public fun peek() : E? = js.noImpl
public fun offer(e : E) : Boolean = js.noImpl public fun offer(e : E) : Boolean = js.noImpl
@@ -15,12 +15,12 @@ import java.util.*
* *
* @includeFunction ../../test/CollectionTest.kt map * @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) 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 */ /** 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) for (item in this)
result.add(transform(item)) result.add(transform(item))
return result return result
@@ -15,12 +15,12 @@ import java.util.*
* *
* @includeFunction ../../test/CollectionTest.kt map * @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) 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 */ /** 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) for (item in this)
result.add(transform(item)) result.add(transform(item))
return result return result
@@ -15,12 +15,12 @@ import java.util.*
* *
* @includeFunction ../../test/CollectionTest.kt map * @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) 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 */ /** 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) for (item in this)
result.add(transform(item)) result.add(transform(item))
return result return result
+74 -74
View File
@@ -8,103 +8,103 @@ import java.util.List
import java.util.ArrayList import java.util.ArrayList
// Array "constructor" // 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 // "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) public inline fun ByteArray.binarySearch(key: Byte) : Int = Arrays.binarySearch(this, key)
inline fun ShortArray.binarySearch(key: Short) = Arrays.binarySearch(this, key) public inline fun ShortArray.binarySearch(key: Short) : Int = Arrays.binarySearch(this, key)
inline fun IntArray.binarySearch(key: Int) = Arrays.binarySearch(this, key) public inline fun IntArray.binarySearch(key: Int) : Int = Arrays.binarySearch(this, key)
inline fun LongArray.binarySearch(key: Long) = Arrays.binarySearch(this, key) public inline fun LongArray.binarySearch(key: Long) : Int = Arrays.binarySearch(this, key)
inline fun FloatArray.binarySearch(key: Float) = Arrays.binarySearch(this, key) public inline fun FloatArray.binarySearch(key: Float) : Int = Arrays.binarySearch(this, key)
inline fun DoubleArray.binarySearch(key: Double) = Arrays.binarySearch(this, key) public inline fun DoubleArray.binarySearch(key: Double) : Int = Arrays.binarySearch(this, key)
inline fun CharArray.binarySearch(key: Char) = 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) public inline fun ByteArray.binarySearch(fromIndex: Int, toIndex: Int, key: Byte) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun ShortArray.binarySearch(fromIndex: Int, toIndex: Int, key: Short) = Arrays.binarySearch(this, fromIndex, toIndex, key) public inline fun ShortArray.binarySearch(fromIndex: Int, toIndex: Int, key: Short) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun IntArray.binarySearch(fromIndex: Int, toIndex: Int, key: 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)
inline fun LongArray.binarySearch(fromIndex: Int, toIndex: Int, key: Long) = Arrays.binarySearch(this, fromIndex, toIndex, key) public inline fun LongArray.binarySearch(fromIndex: Int, toIndex: Int, key: Long) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun FloatArray.binarySearch(fromIndex: Int, toIndex: Int, key: Float) = Arrays.binarySearch(this, fromIndex, toIndex, key) public inline fun FloatArray.binarySearch(fromIndex: Int, toIndex: Int, key: Float) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key)
inline fun DoubleArray.binarySearch(fromIndex: Int, toIndex: Int, key: Double) = Arrays.binarySearch(this, fromIndex, toIndex, key) public inline fun DoubleArray.binarySearch(fromIndex: Int, toIndex: Int, key: Double) : Int = 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 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> { public inline fun <T> Array<T>.binarySearch(key: T, comparator: public fun(T,T):Int) = Arrays.binarySearch(this, key, object: java.util.Comparator<T> {
override fun compare(a: T, b: T) = comparator(a, b) 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) public inline fun BooleanArray.fill(value: Boolean) : Unit = Arrays.fill(this, value)
inline fun ByteArray.fill(value: Byte) = Arrays.fill(this, value) public inline fun ByteArray.fill(value: Byte) : Unit = Arrays.fill(this, value)
inline fun ShortArray.fill(value: Short) = Arrays.fill(this, value) public inline fun ShortArray.fill(value: Short) : Unit = Arrays.fill(this, value)
inline fun IntArray.fill(value: Int) = Arrays.fill(this, value) public inline fun IntArray.fill(value: Int) : Unit = Arrays.fill(this, value)
inline fun LongArray.fill(value: Long) = Arrays.fill(this, value) public inline fun LongArray.fill(value: Long) : Unit = Arrays.fill(this, value)
inline fun FloatArray.fill(value: Float) = Arrays.fill(this, value) public inline fun FloatArray.fill(value: Float) : Unit = Arrays.fill(this, value)
inline fun DoubleArray.fill(value: Double) = Arrays.fill(this, value) public inline fun DoubleArray.fill(value: Double) : Unit = Arrays.fill(this, value)
inline fun CharArray.fill(value: Char) = 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) public inline fun ByteArray.sort() : Unit = Arrays.sort(this)
inline fun ShortArray.sort() = Arrays.sort(this) public inline fun ShortArray.sort() : Unit = Arrays.sort(this)
inline fun IntArray.sort() = Arrays.sort(this) public inline fun IntArray.sort() : Unit = Arrays.sort(this)
inline fun LongArray.sort() = Arrays.sort(this) public inline fun LongArray.sort() : Unit = Arrays.sort(this)
inline fun FloatArray.sort() = Arrays.sort(this) public inline fun FloatArray.sort() : Unit = Arrays.sort(this)
inline fun DoubleArray.sort() = Arrays.sort(this) public inline fun DoubleArray.sort() : Unit = Arrays.sort(this)
inline fun CharArray.sort() = 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) public inline fun ByteArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
inline fun ShortArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex) public inline fun ShortArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
inline fun IntArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex) public inline fun IntArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
inline fun LongArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex) public inline fun LongArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
inline fun FloatArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex) public inline fun FloatArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
inline fun DoubleArray.sort(fromIndex: Int, toIndex: Int) = Arrays.sort(this, fromIndex, toIndex) public inline fun DoubleArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex)
inline fun CharArray.sort(fromIndex: Int, toIndex: Int) = 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() public inline fun BooleanArray.copyOf(newLength: Int = this.size) : BooleanArray = Arrays.copyOf(this, newLength).sure()
inline fun ByteArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure() public inline fun ByteArray.copyOf(newLength: Int = this.size) : ByteArray = Arrays.copyOf(this, newLength).sure()
inline fun ShortArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure() public inline fun ShortArray.copyOf(newLength: Int = this.size) : ShortArray = Arrays.copyOf(this, newLength).sure()
inline fun IntArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure() public inline fun IntArray.copyOf(newLength: Int = this.size) : IntArray = Arrays.copyOf(this, newLength).sure()
inline fun LongArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure() public inline fun LongArray.copyOf(newLength: Int = this.size) : LongArray = Arrays.copyOf(this, newLength).sure()
inline fun FloatArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure() public inline fun FloatArray.copyOf(newLength: Int = this.size) : FloatArray = Arrays.copyOf(this, newLength).sure()
inline fun DoubleArray.copyOf(newLength: Int = this.size) = Arrays.copyOf(this, newLength).sure() public inline fun DoubleArray.copyOf(newLength: Int = this.size) : DoubleArray = Arrays.copyOf(this, newLength).sure()
inline fun CharArray.copyOf(newLength: Int = this.size) = 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() public inline fun BooleanArray.copyOfRange(from: Int, to: Int) : BooleanArray = Arrays.copyOfRange(this, from, to).sure()
inline fun ByteArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure() public inline fun ByteArray.copyOfRange(from: Int, to: Int) : ByteArray = Arrays.copyOfRange(this, from, to).sure()
inline fun ShortArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure() public inline fun ShortArray.copyOfRange(from: Int, to: Int) : ShortArray = Arrays.copyOfRange(this, from, to).sure()
inline fun IntArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure() public inline fun IntArray.copyOfRange(from: Int, to: Int) : IntArray = Arrays.copyOfRange(this, from, to).sure()
inline fun LongArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure() public inline fun LongArray.copyOfRange(from: Int, to: Int) : LongArray = Arrays.copyOfRange(this, from, to).sure()
inline fun FloatArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure() public inline fun FloatArray.copyOfRange(from: Int, to: Int) : FloatArray = Arrays.copyOfRange(this, from, to).sure()
inline fun DoubleArray.copyOfRange(from: Int, to: Int) = Arrays.copyOfRange(this, from, to).sure() public inline fun DoubleArray.copyOfRange(from: Int, to: Int) : DoubleArray = Arrays.copyOfRange(this, from, to).sure()
inline fun CharArray.copyOfRange(from: Int, to: Int) = 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 inline val ByteArray.inputStream : ByteArrayInputStream
get() = ByteArrayInputStream(this) 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) { if (encoding != null) {
return String(this, encoding) return String(this, encoding)
} else { } 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 */ /** 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 */ /** 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 */ /** 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) val list = ArrayList<Character>(this.size)
for (c in this) { for (c in this) {
if (c != null) { if (c != null) {
+1 -1
View File
@@ -1,6 +1,6 @@
package kotlin package kotlin
inline fun Int.times(body : () -> Unit) { public inline fun Int.times(body : () -> Unit) {
var count = this; var count = this;
while (count > 0) { while (count > 0) {
body() body()
+1 -1
View File
@@ -5,7 +5,7 @@ import java.lang.Object
import jet.runtime.Intrinsic 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.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> [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 */ /** Returns the size of the map */
val JMap<*,*>.size : Int val JMap<*,*>.size : Int
get() = size() get() = size()
/** Returns true if this map is empty */ /** Returns true if this map is empty */
val JMap<*,*>.empty : Boolean val JMap<*,*>.empty : Boolean
get() = isEmpty() get() = isEmpty()
/** Provides [] access to maps */ /** 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]] */ /** 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> 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> = if (this != null) this else Collections.EMPTY_MAP as java.util.Map<K,V>
/** Returns the key of the entry */ /** 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 * @includeFunction ../../test/MapTest.kt getOrElse
*/ */
inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V { public inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V {
val current = this.get(key) val current = this.get(key)
if (current != null) { if (current != null) {
return current return current
} else { } else {
return defaultValue() 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 * @includeFunction ../../test/MapTest.kt getOrElse
*/ */
inline fun <K,V> java.util.Map<K,V>.getOrPut(key: K, defaultValue: ()-> V) : V { public inline fun <K,V> java.util.Map<K,V>.getOrPut(key: K, defaultValue: ()-> V) : V {
val current = this.get(key) val current = this.get(key)
if (current != null) { if (current != null) {
return current return current
} else { } else {
val answer = defaultValue() val answer = defaultValue()
this.put(key, answer) this.put(key, answer)
return answer return answer
} }
} }
+17 -17
View File
@@ -12,26 +12,26 @@ val Collection<*>.empty : Boolean
get() = isEmpty() get() = isEmpty()
/** Returns a new ArrayList with a variable number of initial elements */ /** 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 */ /** 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 */ /** 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 */ /** 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 val Collection<*>.indices : IntRange
get() = 0..size-1 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) val answer = Array<T>(this.size)
var idx = 0 var idx = 0
for (elem in this) 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 */ /** 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 // 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) Collections.sort(this)
return 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) Collections.sort(this, comparator)
return this return this
} }
/** Returns the List if its not null otherwise returns the empty list */ /** 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> = 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 */ /** 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> = if (this != null) this else Collections.EMPTY_SET as java.util.Set<T>
/** /**
TODO figure out necessary variance/generics ninja stuff... :) 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>() { 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 v1 = transform(o1)
val v2 = transform(o2) val v2 = transform(o2)
if (v1 == v2) { if (v1 == v2) {
@@ -101,9 +101,9 @@ val <T> List<T>.last : T?
/** Returns true if the collection is not empty */ /** 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 */ /** 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> = if (this != null) this else Collections.EMPTY_LIST as Collection<T>
@@ -14,12 +14,12 @@ import java.util.*
* *
* @includeFunction ../../test/CollectionTest.kt map * @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) 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 */ /** 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) for (item in this)
result.add(transform(item)) result.add(transform(item))
return result return result
@@ -12,7 +12,7 @@ import java.util.Iterator
* If base collection implements [[Collection]] interface method [[Collection.size()]] will be used. * If base collection implements [[Collection]] interface method [[Collection.size()]] will be used.
* Otherwise, this method determines the count by iterating through the all items. * 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>) { if (this is Collection<T>) {
return this.size() return this.size()
} }
@@ -30,7 +30,7 @@ fun <T> java.lang.Iterable<T>.count() : Int {
* Will throw an exception if there are no elements * Will throw an exception if there are no elements
*/ */
// TODO: Specify type of the exception // 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>) { if (this is AbstractList<T>) {
return this.get(0) return this.get(0)
} }
@@ -50,7 +50,7 @@ inline fun <T> java.lang.Iterable<T>.first() : T {
* @includeFunction ../../test/CollectionTest.kt last * @includeFunction ../../test/CollectionTest.kt last
*/ */
// TODO: Specify type of the exception // 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>) { if (this is List<T>) {
return this.get(this.size() - 1); 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 * If collection implements [[java.util.AbstractCollection]] an overridden implementation of the contains
* method will be used. * 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>) { if (this is java.util.AbstractCollection<T>) {
return this.contains(item); 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 * 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)> { 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 // 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)> 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 class NumberedIterator<TT>(private val sourceIterator : java.util.Iterator<TT>) : java.util.Iterator<#(Int, TT)> {
private var nextIndex = 0 private var nextIndex = 0
override fun remove() { public override fun remove() {
try { try {
sourceIterator.remove() sourceIterator.remove()
nextIndex--; 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(); return sourceIterator.hasNext();
} }
override fun next(): #(Int, TT) { public override fun next(): #(Int, TT) {
val result = #(nextIndex, sourceIterator.next()) val result = #(nextIndex, sourceIterator.next())
nextIndex++ nextIndex++
return result 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 * they are compared via [[#equals()]] and if they are not the same then
* the [[#hashCode()]] method is used as the difference * 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 (a == null) return - 1
if (b == null) return 1 if (b == null) return 1
if (a is Comparable<T>) { 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) return FunctionComparator<T>(functions)
} }
private class FunctionComparator<T>(val functions: Array<Function1<T,Any?>>): Comparator<T> { private class FunctionComparator<T>(val functions: Array<Function1<T,Any?>>): Comparator<T> {
fun toString(): String { public fun toString(): String {
return "FunctionComparator${functions.toList()}" 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) return compareBy<T>(o1, o2, *functions)
} }
override fun equals(obj: Any?): Boolean { public override fun equals(obj: Any?): Boolean {
return this == obj 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 * Throws an [[AssertionError]] if the `value` is false and runtime assertions have been
* enabled on the JVM using the `-ea` JVM option. * 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(Assertions._ENABLED) {
if(!value) { if(!value) {
throw AssertionError(); throw AssertionError();
@@ -21,7 +21,7 @@ inline fun assert(value: Boolean): Unit {
* Throws an [[AssertionError]] with specified `message` if the `value` is false * 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. * 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(Assertions._ENABLED) {
if(!value) { if(!value) {
throw AssertionError(message); 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 * 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. * 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(Assertions._ENABLED) {
if(!value) { if(!value) {
val message = lazyMessage() val message = lazyMessage()
@@ -45,7 +45,7 @@ inline fun assert(value: Boolean, lazyMessage: () -> String) {
/** /**
* Throws an [[IllegalArgumentException]] if the `value` is false. * Throws an [[IllegalArgumentException]] if the `value` is false.
*/ */
inline fun require(value: Boolean): Unit { public inline fun require(value: Boolean): Unit {
if(!value) { if(!value) {
throw IllegalArgumentException(); throw IllegalArgumentException();
} }
@@ -54,7 +54,7 @@ inline fun require(value: Boolean): Unit {
/** /**
* Throws an [[IllegalArgumentException]] with specified `message` if the `value` is false. * 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) { if(!value) {
throw IllegalArgumentException(message.toString()); 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. * 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) { if(!value) {
val message = lazyMessage() val message = lazyMessage()
throw IllegalArgumentException(message.toString()); throw IllegalArgumentException(message.toString());
@@ -73,7 +73,7 @@ inline fun require(value: Boolean, lazyMessage: () -> String): Unit {
/** /**
* Throws an [[IllegalStateException]] if the `value` is false. * Throws an [[IllegalStateException]] if the `value` is false.
*/ */
inline fun check(value: Boolean): Unit { public inline fun check(value: Boolean): Unit {
if(!value) { if(!value) {
throw IllegalStateException(); throw IllegalStateException();
} }
@@ -82,7 +82,7 @@ inline fun check(value: Boolean): Unit {
/** /**
* Throws an [[IllegalStateException]] with specified `message` if the `value` is false. * 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) { if(!value) {
throw IllegalStateException(message.toString()); 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. * 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) { if(!value) {
val message = lazyMessage() val message = lazyMessage()
throw IllegalStateException(message.toString()); throw IllegalStateException(message.toString());
+12 -12
View File
@@ -10,21 +10,21 @@ import java.util.TreeSet
/** /**
Helper to make jet.Iterator usable in for 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 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 Helper to make java.util.Enumeration usable in for
*/ */
fun <erased T> java.util.Enumeration<T>.iterator(): Iterator<T> = object: Iterator<T> { public fun <erased T> java.util.Enumeration<T>.iterator(): Iterator<T> = object: Iterator<T> {
override val hasNext: Boolean override val hasNext: Boolean
get() = hasMoreElements() 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 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) while(hasNext)
container.add(next()) container.add(next())
return container 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 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 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 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 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 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 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.List
import java.util.ArrayList 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 */ /** 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 */ /** 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 */ /** 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 var answer = this
if (answer.startsWith(prefix)) { if (answer.startsWith(prefix)) {
answer = answer.substring(prefix.length()) 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 */ /** 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 var answer = this
if (answer.endsWith(postfix)) { if (answer.endsWith(postfix)) {
answer = answer.substring(0, length() - postfix.length()) answer = answer.substring(0, length() - postfix.length())
@@ -44,33 +44,33 @@ inline fun String.trimTrailing(postfix: String): String {
return answer 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 inline val String.size : Int
get() = length() get() = length()
@@ -80,135 +80,135 @@ get() = StringReader(this)
// "constructors" for String // "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 */ /** 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) { if(encoding==null) {
return (this as java.lang.String).getBytes().sure() return (this as java.lang.String).getBytes().sure()
} else { } else {
return (this as java.lang.String).getBytes(encoding).sure() 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() public inline fun String.toBoolean() : Boolean = java.lang.Boolean.parseBoolean(this).sure()
inline fun String.toShort() = java.lang.Short.parseShort(this).sure() public inline fun String.toShort() : Short = java.lang.Short.parseShort(this).sure()
inline fun String.toInt() = java.lang.Integer.parseInt(this).sure() public inline fun String.toInt() : Int = java.lang.Integer.parseInt(this).sure()
inline fun String.toLong() = java.lang.Long.parseLong(this).sure() public inline fun String.toLong() : Long = java.lang.Long.parseLong(this).sure()
inline fun String.toFloat() = java.lang.Float.parseFloat(this).sure() public inline fun String.toFloat() : Float = java.lang.Float.parseFloat(this).sure()
inline fun String.toDouble() = java.lang.Double.parseDouble(this).sure() public inline fun String.toDouble() : Double = java.lang.Double.parseDouble(this).sure()
/** /**
* Converts the string into a regular expression [[Pattern]] optionally * Converts the string into a regular expression [[Pattern]] optionally
* with the specified flags from [[Pattern]] or'd together * with the specified flags from [[Pattern]] or'd together
* so that strings can be split or matched on. * 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() return java.util.regex.Pattern.compile(this, flags).sure()
} }
/** /**
Iterator for characters of given CharSequence Iterator for characters of given CharSequence
*/ */
inline fun CharSequence.iterator() : CharIterator = object: jet.CharIterator() { public inline fun CharSequence.iterator() : CharIterator = object: jet.CharIterator() {
private var index = 0 private var index = 0
public override fun nextChar(): Char = get(index++) public override fun nextChar(): Char = get(index++)
public override val hasNext: Boolean public override val hasNext: Boolean
get() = index < length 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 */ /** 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 // "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 inline val CharSequence.size : Int
get() = length() 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 val empty : Boolean
get() = size == 0 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) if(empty)
return this return this
@@ -23,10 +23,10 @@ abstract class FunctionalList<T>(public val size: Int) {
return new return new
} }
fun iterator() : Iterator<T> = object: Iterator<T> { public fun iterator() : Iterator<T> = object: Iterator<T> {
var cur = this@FunctionalList var cur = this@FunctionalList
override fun next(): T { public override fun next(): T {
if(cur.empty) if(cur.empty)
throw java.util.NoSuchElementException() 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) 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 val empty : Boolean
get() = size == 0 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(output.empty) {
if(input.empty) if(input.empty)
throw java.util.NoSuchElementException() throw java.util.NoSuchElementException()
@@ -9,7 +9,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Executes given calculation under lock Executes given calculation under lock
Returns result of the calculation 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() lock()
try { try {
return action() return action()
@@ -23,7 +23,7 @@ inline fun <erased T> Lock.withLock(action: ()->T) : T {
Executes given calculation under read lock Executes given calculation under read lock
Returns result of the calculation 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() val rl = readLock().sure()
rl.lock() rl.lock()
try { 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 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 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 rl = readLock().sure()
val readCount = if (getWriteHoldCount() == 0) getReadHoldCount() else 0 val readCount = if (getWriteHoldCount() == 0) getReadHoldCount() else 0
@@ -24,9 +24,9 @@ inline var Thread.contextClassLoader : ClassLoader?
get() = getContextClassLoader() get() = getContextClassLoader()
set(loader: ClassLoader?) { setContextClassLoader(loader) } 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() { val thread = object: Thread() {
override fun run() { public override fun run() {
block() block()
} }
} }
@@ -43,9 +43,9 @@ fun thread(start: Boolean = true, daemon: Boolean = false, contextClassLoader: C
return thread return thread
} }
inline fun Executor.execute(action: ()->Unit) { public inline fun Executor.execute(action: ()->Unit) {
execute(object: Runnable{ execute(object: Runnable{
override fun run() { public override fun run() {
action() action()
} }
}) })
+11 -11
View File
@@ -4,68 +4,68 @@ import java.util.Timer
import java.util.TimerTask import java.util.TimerTask
import java.util.Date 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) val task = createTask(action)
schedule(task, delay) schedule(task, delay)
return task 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) val task = createTask(action)
schedule(task, time) schedule(task, time)
return task 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) val task = createTask(action)
schedule(task, delay, period) schedule(task, delay, period)
return task 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) val task = createTask(action)
schedule(task, time, period) schedule(task, time, period)
return task 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) val task = createTask(action)
scheduleAtFixedRate(task, delay, period) scheduleAtFixedRate(task, delay, period)
return task 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) val task = createTask(action)
scheduleAtFixedRate(task, time, period) scheduleAtFixedRate(task, time, period)
return task 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) val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.schedule(initialDelay, period, action) timer.schedule(initialDelay, period, action)
return timer 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) val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.schedule(startAt, period, action) timer.schedule(startAt, period, action)
return timer 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) val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.scheduleAtFixedRate(initialDelay, period, action) timer.scheduleAtFixedRate(initialDelay, period, action)
return timer 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) val timer = if(name == null) Timer(daemon) else Timer(name, daemon)
timer.scheduleAtFixedRate(startAt, period, action) timer.scheduleAtFixedRate(startAt, period, action)
return timer return timer
} }
private fun createTask(action: TimerTask.()->Unit) : TimerTask = object: TimerTask() { private fun createTask(action: TimerTask.()->Unit) : TimerTask = object: TimerTask() {
override fun run() { public override fun run() {
action() action()
} }
} }
+36 -36
View File
@@ -96,7 +96,7 @@ set(value) {
// Helper methods // Helper methods
/** Returns true if the element has the given CSS class style in its 'class' attribute */ /** 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 val c = this.classes
return if (c != null) return if (c != null)
c.matches("""(^|.*\s+)$cssClass($|\s+.*)""") 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 */ /** 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 classSet = this.classSet
val answer = classSet.add(cssClass) val answer = classSet.add(cssClass)
if (answer) { if (answer) {
@@ -114,7 +114,7 @@ fun Element.addClass(cssClass: String): Boolean {
} }
/** Removes the given CSS class to this element's 'class' attribute */ /** 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 classSet = this.classSet
val answer = classSet.remove(cssClass) val answer = classSet.remove(cssClass)
if (answer) { if (answer) {
@@ -125,7 +125,7 @@ fun Element.removeClass(cssClass: String): Boolean {
/** TODO this approach generates compiler errors... /** 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 val set = this.classSet
var answer = false var answer = false
for (cs in cssClasses) { for (cs in cssClasses) {
@@ -139,7 +139,7 @@ fun Element.addClass(varargs cssClasses: Array<String>): Boolean {
return answer return answer
} }
fun Element.removeClass(varargs cssClasses: Array<String>): Boolean { public fun Element.removeClass(varargs cssClasses: Array<String>): Boolean {
val set = this.classSet val set = this.classSet
var answer = false var answer = false
for (cs in cssClasses) { 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 #) */ /** 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() val root = this?.getDocumentElement()
return if (root != null) { return if (root != null) {
if (selector == "*") { 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 #) */ /** 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 == "*") { return if (selector == "*") {
elements elements
} else if (selector.startsWith(".")) { } 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 */ /** 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>() { class NextSiblingIterator(var node: Node) : AbstractIterator<Node>() {
override fun computeNext(): Node? { public override fun computeNext(): Node? {
val next = node.getNextSibling() val next = node.getNextSibling()
if (next != null) { if (next != null) {
node = next node = next
@@ -213,11 +213,11 @@ class NextSiblingIterator(var node: Node) : AbstractIterator<Node>() {
} }
} }
/** Returns an [[Iterator]] over the next siblings of this 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>() { class PreviousSiblingIterator(var node: Node) : AbstractIterator<Node>() {
override fun computeNext(): Node? { public override fun computeNext(): Node? {
val next = node.getPreviousSibling() val next = node.getPreviousSibling()
if (next != null) { if (next != null) {
node = next 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 */ /** 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() val nodeType = getNodeType()
return nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE return nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE
} }
/** Returns an [[Iterator]] of all the next [[Element]] siblings */ /** 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 */ /** 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 */ /** 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) ?: "" return this.getAttribute(name) ?: ""
} }
/** Returns the children of the element as a list */ /** 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() return this?.getChildNodes().toList()
} }
@@ -261,22 +261,22 @@ get() = this?.getElementsByTagName("*").toElementList()
/** Returns all the child elements given the local element name */ /** 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() return this?.getElementsByTagName(localName).toElementList()
} }
/** Returns all the elements given the local element name */ /** 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() return this?.getElementsByTagName(localName).toElementList()
} }
/** Returns all the child elements given the namespace URI and local element name */ /** 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() return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
} }
/** Returns all the elements given the namespace URI and local element name */ /** 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() return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
} }
@@ -300,7 +300,7 @@ val NodeList?.last : Node?
get() = this.tail get() = this.tail
inline fun NodeList?.toList(): List<Node> { public inline fun NodeList?.toList(): List<Node> {
return if (this == null) { return if (this == null) {
Collections.EMPTY_LIST as List<Node> 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) { return if (this == null) {
Collections.EMPTY_LIST as List<Element> Collections.EMPTY_LIST as List<Element>
} }
@@ -319,7 +319,7 @@ inline fun NodeList?.toElementList(): List<Element> {
} }
/** Converts the node list to an XML String */ /** 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) return if (this == null)
"" else { "" else {
nodesToXmlString(this.toList(), xmlDeclaration) nodesToXmlString(this.toList(), xmlDeclaration)
@@ -327,7 +327,7 @@ fun NodeList?.toXmlString(xmlDeclaration: Boolean = false): String {
} }
class NodeListAsList(val nodeList: NodeList): AbstractList<Node>() { 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) val node = nodeList.item(index)
if (node == null) { if (node == null) {
throw IndexOutOfBoundsException("NodeList does not contain a node at index: " + index) 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>() { 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) val node = nodeList.item(index)
if (node is Element) { if (node is Element) {
return node 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 // Syntax sugar
inline fun Node.plus(child: Node?): Node { public inline fun Node.plus(child: Node?): Node {
if (child != null) { if (child != null) {
this.appendChild(child) this.appendChild(child)
} }
return this 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 // 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 * 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() val elem = this.createElement(name).sure()
elem.init() elem.init()
return elem 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 * 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() val elem = ownerDocument(doc).createElement(name).sure()
elem.init() elem.init()
return elem return elem
} }
/** Returns the owner document of the element or uses the provided document */ /** 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 val answer = if (this is Document) this as Document
else if (doc == null) this.getOwnerDocument() else if (doc == null) this.getOwnerDocument()
else doc 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 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) val child = createElement(name, init)
this.appendChild(child) this.appendChild(child)
return 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 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) val child = createElement(name, doc, init)
this.appendChild(child) this.appendChild(child)
return 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 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) { if (text != null) {
val child = ownerDocument(doc).createTextNode(text) val child = ownerDocument(doc).createTextNode(text)
this.appendChild(child) this.appendChild(child)
+6 -6
View File
@@ -20,17 +20,17 @@ import java.util.Collection
import java.io.Writer import java.io.Writer
/** Creates a new document with the given document builder*/ /** Creates a new document with the given document builder*/
fun createDocument(builder: DocumentBuilder): Document { public fun createDocument(builder: DocumentBuilder): Document {
return builder.newDocument().sure() return builder.newDocument().sure()
} }
/** Creates a new document with an optional DocumentBuilderFactory */ /** 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()) return createDocument(builderFactory.newDocumentBuilder().sure())
} }
/** Creates a new TrAX transformer */ /** 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) { val transformer = if (source != null) {
factory.newTransformer(source) factory.newTransformer(source)
} else { } else {
@@ -40,21 +40,21 @@ fun createTransformer(source: Source? = null, factory: TransformerFactory = Tran
} }
/** Converts the node to an XML String */ /** 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() val writer = StringWriter()
writeXmlString(writer, xmlDeclaration) writeXmlString(writer, xmlDeclaration)
return writer.toString().sure() return writer.toString().sure()
} }
/** Converts the node to an XML String and writes it to the given [[Writer]] */ /** 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() val transformer = createTransformer()
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, if (xmlDeclaration) "no" else "yes") transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, if (xmlDeclaration) "no" else "yes")
transformer.transform(DOMSource(this), StreamResult(writer)) transformer.transform(DOMSource(this), StreamResult(writer))
} }
/** Converts the collection of nodes to an XML String */ /** 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... // TODO this should work...
// return this.map<Node,String>{it.toXmlString()}.join("") // return this.map<Node,String>{it.toXmlString()}.join("")
val builder = StringBuilder() 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]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Any?) { public inline fun print(message : Any?) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Int) { public inline fun print(message : Int) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Long) { public inline fun print(message : Long) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Byte) { public inline fun print(message : Byte) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Short) { public inline fun print(message : Short) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Char) { public inline fun print(message : Char) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Boolean) { public inline fun print(message : Boolean) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Float) { public inline fun print(message : Float) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : Double) { public inline fun print(message : Double) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message to [[System.out]] */ /** Prints the given message to [[System.out]] */
inline fun print(message : CharArray) { public inline fun print(message : CharArray) {
System.out?.print(message) System.out?.print(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Any?) { public inline fun println(message : Any?) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Int) { public inline fun println(message : Int) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Long) { public inline fun println(message : Long) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Byte) { public inline fun println(message : Byte) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Short) { public inline fun println(message : Short) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Char) { public inline fun println(message : Char) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Boolean) { public inline fun println(message : Boolean) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Float) { public inline fun println(message : Float) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : Double) { public inline fun println(message : Double) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints the given message and newline to [[System.out]] */ /** Prints the given message and newline to [[System.out]] */
inline fun println(message : CharArray) { public inline fun println(message : CharArray) {
System.out?.println(message) System.out?.println(message)
} }
/** Prints a newline t[[System.out]] */ /** Prints a newline t[[System.out]] */
inline fun println() { public inline fun println() {
System.out?.println() System.out?.println()
} }
private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : InputStream() { private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : InputStream() {
override fun read() : Int { public override fun read() : Int {
return System.`in`?.read() ?: -1 return System.`in`?.read() ?: -1
} }
override fun reset() { public override fun reset() {
System.`in`?.reset() System.`in`?.reset()
} }
override fun read(b: ByteArray?): Int { public override fun read(b: ByteArray?): Int {
return System.`in`?.read(b) ?: -1 return System.`in`?.read(b) ?: -1
} }
override fun close() { public override fun close() {
System.`in`?.close() System.`in`?.close()
} }
override fun mark(readlimit: Int) { public override fun mark(readlimit: Int) {
System.`in`?.mark(readlimit) System.`in`?.mark(readlimit)
} }
override fun skip(n: Long): Long { public override fun skip(n: Long): Long {
return System.`in`?.skip(n) ?: -1.toLong() return System.`in`?.skip(n) ?: -1.toLong()
} }
override fun available(): Int { public override fun available(): Int {
return System.`in`?.available() ?: 0 return System.`in`?.available() ?: 0
} }
override fun markSupported(): Boolean { public override fun markSupported(): Boolean {
return System.`in`?.markSupported() ?: false 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 return System.`in`?.read(b, off, len) ?: -1
} }
})) }))
/** Reads a line of input from [[System.in]] */ /** 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 */ /** 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 var closed = false
try { try {
return block(this) 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 */ /** Returns an [Iterator] of bytes over an input stream */
fun InputStream.iterator() : ByteIterator = public fun InputStream.iterator() : ByteIterator =
object: ByteIterator() { object: ByteIterator() {
override val hasNext : Boolean override val hasNext : Boolean
get() = available() > 0 get() = available() > 0
override fun nextByte() = read().toByte() public override fun nextByte() : Byte = read().toByte()
} }
/** Creates a buffered input stream */ /** Creates a buffered input stream */
inline fun InputStream.buffered(bufferSize: Int = defaultBufferSize) public inline fun InputStream.buffered(bufferSize: Int = defaultBufferSize) : InputStream
= if (this is BufferedInputStream) = if (this is BufferedInputStream)
this this
else else
BufferedInputStream(this, bufferSize) 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 public inline fun OutputStream.buffered(bufferSize: Int = defaultBufferSize) : BufferedOutputStream
= if (this is BufferedOutputStream) this else BufferedOutputStream(this, bufferSize) = 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 public inline fun Reader.buffered(bufferSize: Int = defaultBufferSize): BufferedReader
= if(this is BufferedReader) this else BufferedReader(this, bufferSize) = if(this is BufferedReader) this else BufferedReader(this, bufferSize)
inline fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter public inline fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter
= if(this is BufferedWriter) this else BufferedWriter(this, bufferSize) = if(this is BufferedWriter) this else BufferedWriter(this, bufferSize)
inline fun Reader.forEachLine(block: (String) -> Unit): Unit { public inline fun Reader.forEachLine(block: (String) -> Unit): Unit {
this.use{ this.use{
val iter = buffered().lineIterator() val iter = buffered().lineIterator()
while (iter.hasNext) { 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. * Returns an iterator over each line.
@@ -230,7 +230,7 @@ inline fun <T> Reader.useLines(block: (Iterator<String>) -> T): T = this.buffere
* <br> * <br>
* We suggest you try the method useLines() instead which closes the stream when the processing is complete. * 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> { class LineIterator(val reader: BufferedReader) : Iterator<String> {
private var nextValue: String? = null private var nextValue: String? = null
@@ -245,7 +245,7 @@ class LineIterator(val reader: BufferedReader) : Iterator<String> {
return nextValue != null return nextValue != null
} }
override fun next(): String { public override fun next(): String {
if (!hasNext) { if (!hasNext) {
throw NoSuchElementException() throw NoSuchElementException()
} }
@@ -260,7 +260,7 @@ class LineIterator(val reader: BufferedReader) : Iterator<String> {
/** /**
* Recursively process this file and all children with the given block * 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) block(this)
if (this.isDirectory()) { if (this.isDirectory()) {
for (child in this.listFiles()) { 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 * 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) return file.directory.canonicalPath.startsWith(this.directory.canonicalPath)
} }
/** /**
* Returns the relative path of the given descendant of this file if its a descendant * 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 prefix = this.directory.canonicalPath
val answer = descendant.canonicalPath val answer = descendant.canonicalPath
return if (answer.startsWith(prefix)) { return if (answer.startsWith(prefix)) {
@@ -334,14 +334,14 @@ fun File.relativePath(descendant: File): String {
* *
* This method is not recommended on huge files. * 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()) } return FileInputStream(this).use<FileInputStream,ByteArray>{ it.readBytes(this.length().toInt()) }
} }
/** /**
* Writes the bytes as the contents of the file * 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) } 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. * 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 * 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. * 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 * Writes the text as the contents of the file using the optional
* character encoding. The default platform encoding is used if the character * character encoding. The default platform encoding is used if the character
* encoding is not specified or null. * 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 * Writes the text as the contents of the file using the optional
* character encoding. The default platform encoding is used if the character * character encoding. The default platform encoding is used if the character
* encoding is not specified or null. * 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 * 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() file.directory.mkdirs()
val input = FileInputStream(this) val input = FileInputStream(this)
return input.use<FileInputStream,Long>{ 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 * **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) val buffer = ByteArrayOutputStream(estimatedSize)
this.copyTo(buffer) this.copyTo(buffer)
return buffer.toByteArray().sure() 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 * **Note** it is the callers responsibility to close this resource
*/ */
fun Reader.readText(): String { public fun Reader.readText(): String {
val buffer = StringWriter() val buffer = StringWriter()
copyTo(buffer) copyTo(buffer)
return buffer.toString().sure() return buffer.toString().sure()
@@ -416,7 +416,7 @@ fun Reader.readText(): String {
* *
* **Note** it is the callers responsibility to close both of these resources * **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 var bytesCopied: Long = 0
val buffer = ByteArray(bufferSize) val buffer = ByteArray(bufferSize)
var bytes = read(buffer) 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 * **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 var charsCopied: Long = 0
val buffer = CharArray(bufferSize) val buffer = CharArray(bufferSize)
var chars = read(buffer) 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. * 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. * Reads the entire content of the URL as a String with the specified character encoding.
* *
* This method is not recommended on huge files. * 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 * Reads the entire content of the URL as bytes
* *
* This method is not recommended on huge files. * 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.BigInteger
import java.math.BigDecimal 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 java.util.*
import jet.modules.* import jet.modules.*
fun module(name: String, callback: ModuleBuilder.() -> Unit) { public fun module(name: String, callback: ModuleBuilder.() -> Unit) {
val builder = ModuleBuilder(name) val builder = ModuleBuilder(name)
builder.callback() builder.callback()
AllModules.modules.sure().get()?.add(builder) AllModules.modules.sure().get()?.add(builder)
} }
class SourcesBuilder(val parent: ModuleBuilder) { class SourcesBuilder(val parent: ModuleBuilder) {
fun plusAssign(pattern: String) { public fun plusAssign(pattern: String) {
parent.addSourceFiles(pattern) parent.addSourceFiles(pattern)
} }
} }
class ClasspathBuilder(val parent: ModuleBuilder) { class ClasspathBuilder(val parent: ModuleBuilder) {
fun plusAssign(name: String) { public fun plusAssign(name: String) {
parent.addClasspathEntry(name) parent.addClasspathEntry(name)
} }
} }
@@ -32,16 +32,16 @@ open class ModuleBuilder(val name: String): Module {
val classpath: ClasspathBuilder val classpath: ClasspathBuilder
get() = ClasspathBuilder(this) get() = ClasspathBuilder(this)
fun addSourceFiles(pattern: String) { public fun addSourceFiles(pattern: String) {
sourceFiles0.add(pattern) sourceFiles0.add(pattern)
} }
fun addClasspathEntry(name: String) { public fun addClasspathEntry(name: String) {
classpathRoots0.add(name) classpathRoots0.add(name)
} }
override fun getSourceFiles(): List<String?>? = sourceFiles0 public override fun getSourceFiles(): List<String?>? = sourceFiles0
override fun getClasspathRoots(): List<String?>? = classpathRoots0 public override fun getClasspathRoots(): List<String?>? = classpathRoots0
override fun getModuleName(): String? = name public override fun getModuleName(): String? = name
} }
@@ -3,40 +3,40 @@ package kotlin.nullable
import java.util.* import java.util.*
/** Returns true if the element is not null and matches the given predicate */ /** 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) return this != null && predicate(this)
} }
/** Returns true if the element is not null and matches the given predicate */ /** 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) return this != null && predicate(this)
} }
/** Returns the 1 if the element is not null else 0 */ /** 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 return if (this != null) 1 else 0
} }
/** Returns the first item which matches the predicate if this element is not null else null */ /** 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 return if (this != null && predicate(this)) this else null
} }
/** Returns a new List containing all elements in this collection which match the given predicate */ /** 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 */ /** 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)) if (this != null && predicate(this))
result.add(this) result.add(this)
return result return result
} }
/** Returns a List containing all the non null elements in this collection */ /** 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 */ /** 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) { if (this != null) {
result.add(this) 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 */ /** 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 */ /** 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)) { if (this != null && !predicate(this)) {
result.add(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 * Returns the result of transforming each item in the collection to a one or more values which
* are concatenated together into a single collection * 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) 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 * Returns the result of transforming each item in the collection to a one or more values which
* are concatenated together into a single collection * 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) { if (this != null) {
val coll = transform(this) val coll = transform(this)
if (coll != null) { 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 */ /** 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) { if (this != null) {
operation(this) 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 * 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} * {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) { return if (this != null) {
operation(initial, this) operation(initial, this)
} else { } 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 * 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 :) // maximum size is 1 so it makes no difference :)
return fold(initial, operation) 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 * 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 * 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) { if (this != null) {
val key = toKey(this) val key = toKey(this)
val list = result.getOrPut(key){ ArrayList<T>() } 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 */ /** 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) val buffer = StringBuilder(prefix)
var first = true var first = true
if (this != null) { 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 */ /** 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) { return if (this != null) {
transform(this) transform(this)
} else { } 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 */ /** 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) { if (this != null) {
result.add(transform(this)) 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 */ /** 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 return this
} }
/** Copies the collection into the given collection */ /** 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) if (this != null)
result.add(this) result.add(this)
return result return result
} }
/** Converts the collection into a LinkedList */ /** 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 */ /** 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 */ /** 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 */ /** 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... :) 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() val answer = this.toList()
answer.sort(transform) answer.sort(transform)
return answer 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?) { public class ChangeEvent(val source: Any, val name: String, val oldValue: Any?, val newValue: Any?) {
var propogationId: Any? = null var propogationId: Any? = null
fun toString() = "ChangeEvent($name, $oldValue, $newValue)" public fun toString() : String = "ChangeEvent($name, $oldValue, $newValue)"
} }
public trait ChangeListener { 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 private var nameListeners: Map<String, List<ChangeListener>>? = null
fun addChangeListener(listener: ChangeListener) { public fun addChangeListener(listener: ChangeListener) {
if (allListeners == null) { if (allListeners == null) {
allListeners = ArrayList<ChangeListener>() allListeners = ArrayList<ChangeListener>()
} }
allListeners?.add(listener) allListeners?.add(listener)
} }
fun addChangeListener(name: String, listener: ChangeListener) { public fun addChangeListener(name: String, listener: ChangeListener) {
if (nameListeners == null) { if (nameListeners == null) {
nameListeners = HashMap<String, List<ChangeListener>>() 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 // TODO
//addChangeListener(DelegateChangeListener(fn)) //addChangeListener(DelegateChangeListener(fn))
} }
fun onPropertyChange(name: String, fn: (ChangeEvent) -> Unit) { public fun onPropertyChange(name: String, fn: (ChangeEvent) -> Unit) {
// TODO // TODO
//addChangeListener(name, DelegateChangeListener(fn)) //addChangeListener(name, DelegateChangeListener(fn))
} }
@@ -89,7 +89,7 @@ see http://youtrack.jetbrains.com/issue/KT-1362
protected fun createChangeListener(fn: (ChangeEvent) -> Unit): ChangeListener { protected fun createChangeListener(fn: (ChangeEvent) -> Unit): ChangeListener {
return ChangeListener { return ChangeListener {
override fun onPropertyChange(event: ChangeEvent): Unit { public override fun onPropertyChange(event: ChangeEvent): Unit {
fn(event) fn(event)
} }
} }
@@ -99,7 +99,7 @@ see http://youtrack.jetbrains.com/issue/KT-1362
class DelegateChangeListener(val f: (ChangeEvent) -> Unit) : ChangeListener { class DelegateChangeListener(val f: (ChangeEvent) -> Unit) : ChangeListener {
override fun onPropertyChange(event: ChangeEvent): Unit { public override fun onPropertyChange(event: ChangeEvent): Unit {
f(event) f(event)
} }
} }
@@ -15,7 +15,7 @@ class StringTemplate(val values : Array<Any?>) {
/** /**
* Converts the template into a String * Converts the template into a String
*/ */
fun toString() : String { public fun toString() : String {
val out = StringBuilder() val out = StringBuilder()
forEach{ out.append(it) } forEach{ out.append(it) }
return out.toString() ?: "" return out.toString() ?: ""
@@ -24,7 +24,7 @@ class StringTemplate(val values : Array<Any?>) {
/** /**
* Performs the given function on each value in the collection * 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) { for (v in values) {
fn(v) fn(v)
} }
@@ -38,7 +38,7 @@ class StringTemplate(val values : Array<Any?>) {
* *
* See [[HtmlFormatter] and [[LocaleFormatter] respectively. * See [[HtmlFormatter] and [[LocaleFormatter] respectively.
*/ */
fun StringTemplate.toString(formatter : Formatter) : String { public fun StringTemplate.toString(formatter : Formatter) : String {
val buffer = StringBuilder() val buffer = StringBuilder()
append(buffer, formatter) append(buffer, formatter)
return buffer.toString() ?: "" 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 * Appends the text representation of this string template to the given output
* using the supplied formatter * using the supplied formatter
*/ */
fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit { public fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit {
var constantText = true var constantText = true
this.forEach { this.forEach {
if (constantText) { if (constantText) {
@@ -71,33 +71,33 @@ fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit {
* Converts this string template to internationalised text using the supplied * Converts this string template to internationalised text using the supplied
* [[LocaleFormatter]] * [[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 * 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 * 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 * 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] * to escape particular characters in different output formats such as [[HtmlFormatter]
*/ */
trait Formatter { public trait Formatter {
fun format(buffer : Appendable, val value : Any?) : Unit public fun format(buffer : Appendable, val value : Any?) : Unit
} }
/** /**
* Formats strings with no special encoding other than allowing the null text to be * Formats strings with no special encoding other than allowing the null text to be
* configured * configured
*/ */
open class ToStringFormatter : Formatter { public open class ToStringFormatter : Formatter {
var nullString : String = "null" 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) { if (value == null) {
format(out, nullString) format(out, nullString)
} else if (value is StringTemplate) { } else if (value is StringTemplate) {
@@ -111,25 +111,25 @@ open class ToStringFormatter : Formatter {
* Formats the given string allowing derived classes to override this method * Formats the given string allowing derived classes to override this method
* to escape strings with special characters such as for HTML * 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) 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 * 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 numberFormat : NumberFormat = NumberFormat.getInstance(locale).sure()
public var dateFormat : DateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, 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) { if (value is Number) {
format(out, format(value)) format(out, format(value))
} else if (value is Date) { } 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) ?: "" return numberFormat.format(number) ?: ""
} }
fun format(date : Date) : String { public fun format(date : Date) : String {
return dateFormat.format(date) ?: "" 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. * 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) { if (value is Node) {
out.append(value.toXmlString()) out.append(value.toXmlString())
} else { } 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) { for (c in text) {
if (c == '<') buffer.append("&lt;") if (c == '<') buffer.append("&lt;")
else if (c == '>') buffer.append("&gt;") 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 */ /** 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() val actual = block()
asserter.assertTrue(message, actual) asserter.assertTrue(message, actual)
} }
/** Asserts that the given block returns true */ /** 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 */ /** 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() } assertTrue(message){ !block() }
} }
/** Asserts that the given block returns true */ /** 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 */ /** 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) return assertEquals(true, actual, message)
} }
/** Asserts that the expression is false with an optional 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) return assertEquals(false, actual, message)
} }
/** Asserts that the expected value is equal to the actual value, with an optional 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) asserter.assertEquals(message, expected, actual)
} }
/** Asserts that the expression is not null, with an optional message */ /** 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) asserter.assertNotNull(message, actual)
} }
/** Asserts that the expression is null, with an optional message */ /** 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) asserter.assertNull(message, actual)
} }
/** Marks a test as having failed if this point in the execution path is reached, with an optional message */ /** 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) asserter.fail(message)
} }
/** Asserts that given function block returns the given expected value */ /** 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) expect(expected, block.toString(), block)
} }
/** Asserts that given function block returns the given expected value and use the given message if it fails */ /** 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() val actual = block()
assertEquals(expected, actual, message) assertEquals(expected, actual, message)
} }
/** Asserts that given function block fails by throwing an exception */ /** Asserts that given function block fails by throwing an exception */
fun fails(block: ()-> Unit): Throwable? { public fun fails(block: ()-> Unit): Throwable? {
try { try {
block() block()
asserter.fail("Expected an exception to be thrown") 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 */ /** 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 { try {
block() block()
asserter.fail("Expected an exception to be thrown") 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 * 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 * 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) 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 * A plugin for performing assertions which can reuse JUnit or TestNG
*/ */
trait Asserter { 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 { class DefaultAsserter() : Asserter {
override fun assertTrue(message : String, actual : Boolean) { public override fun assertTrue(message : String, actual : Boolean) {
if (!actual) { if (!actual) {
fail(message) fail(message)
} }
} }
override fun assertEquals(message : String, expected : Any?, actual : Any?) { public override fun assertEquals(message : String, expected : Any?, actual : Any?) {
if (expected != actual) { if (expected != actual) {
fail("$message. Expected <$expected> actual <$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) { if (actual == null) {
fail(message) fail(message)
} }
} }
override fun assertNull(message : String, actual : Any?) { public override fun assertNull(message : String, actual : Any?) {
if (actual != null) { if (actual != null) {
fail(message) 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 // TODO work around compiler bug as it should never try call the private constructor
throw AssertionError(message as Object) 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 Executes current block and returns elapsed time in milliseconds
*/ */
fun measureTimeMillis(block: () -> Unit) : Long { public fun measureTimeMillis(block: () -> Unit) : Long {
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
block() block()
return System.currentTimeMillis() - start return System.currentTimeMillis() - start
@@ -12,7 +12,7 @@ fun measureTimeMillis(block: () -> Unit) : Long {
/** /**
Executes current block and returns elapsed time in nanoseconds Executes current block and returns elapsed time in nanoseconds
*/ */
fun measureTimeNano(block: () -> Unit) : Long { public fun measureTimeNano(block: () -> Unit) : Long {
val start = System.nanoTime() val start = System.nanoTime()
block() block()
return System.nanoTime() - start return System.nanoTime() - start
+1 -1
View File
@@ -10,7 +10,7 @@ import org.junit.*
import org.junit.runner.* import org.junit.runner.*
import org.junit.runner.notification.* import org.junit.runner.notification.*
protected class TestBuilt<T>(name: String, val builder: TestBuilder<T>, val test: TestBuilt<T>.() -> Unit) : TestCase(name) { class TestBuilt<T>(name: String, val builder: TestBuilder<T>, val test: TestBuilt<T>.() -> Unit) : TestCase(name) {
private var myState: T? = null private var myState: T? = null
var state : T var state : T