All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kotlin.JUtil.kt Maven / Gradle / Ivy

There is a newer version: 2.1.0-Beta1
Show newest version
package kotlin

import java.util.*

/** Returns the size of the collection */
public val Collection<*>.size : Int
    get() = size()

/** Returns true if this collection is empty */
public val Collection<*>.empty : Boolean
    get() = isEmpty()

public val Collection<*>.indices : IntRange
    get() = 0..size-1

public val Int.indices: IntRange
    get() = 0..this-1

/** Returns true if the collection is not empty */
public fun  Collection.isNotEmpty() : Boolean = !this.isEmpty()

/** Returns true if this collection is not empty */
val Collection<*>.notEmpty : Boolean
    get() = isNotEmpty()

/** Returns the Collection if its not null otherwise it returns the empty list */
public fun  Collection?.orEmpty() : Collection = this ?: Collections.emptyList()


/** TODO these functions don't work when they generate the Array versions when they are in JLIterables */
public fun > Iterable.toSortedList() : List = toCollection(ArrayList()).sort()

public fun > Iterable.toSortedList(comparator: java.util.Comparator) : List = toList().sort(comparator)


// List APIs

/** Returns the List if its not null otherwise returns the empty list */
public fun  List?.orEmpty() : List = this ?: Collections.emptyList()

/**
  TODO figure out necessary variance/generics ninja stuff... :)
public inline fun  List.sort(transform: fun(T) : java.lang.Comparable<*>) : List {
  val comparator = java.util.Comparator() {
    public fun compare(o1: T, o2: T): Int {
      val v1 = transform(o1)
      val v2 = transform(o2)
      if (v1 == v2) {
        return 0
      } else {
        return v1.compareTo(v2)
      }
    }
  }
  answer.sort(comparator)
}
*/

/**
 * Returns the first item in the list or null if the list is empty
 *
 * @includeFunctionBody ../../test/ListTest.kt first
 */
val  List.first : T?
    get() = this.head


/**
 * Returns the last item in the list or null if the list is empty
 *
 * @includeFunctionBody ../../test/ListTest.kt last
 */
val  List.last : T?
    get() {
      val s = this.size
      return if (s > 0) this.get(s - 1) else null
    }

/**
 * Returns the index of the last item in the list or -1 if the list is empty
 *
 * @includeFunctionBody ../../test/ListTest.kt lastIndex
 */
val  List.lastIndex : Int
    get() = this.size - 1

/**
 * Returns the first item in the list or null if the list is empty
 *
 * @includeFunctionBody ../../test/ListTest.kt head
 */
val  List.head : T?
    get() = if (this.isNotEmpty()) this.get(0) else null

/**
 * Returns all elements in this collection apart from the first one
 *
 * @includeFunctionBody ../../test/ListTest.kt tail
 */
val  List.tail : List
    get() {
        return this.drop(1)
    }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy