Get rid of deprecated annotations and modifiers in stdlib (besides JS)

This commit is contained in:
Denis Zharkov
2015-09-14 16:35:30 +03:00
parent 9c4564a5a6
commit 5cecaa6f87
133 changed files with 1203 additions and 1085 deletions
@@ -10,7 +10,7 @@ import kotlin.test.*
open class SampleTest { open class SampleTest {
open val driver: WebDriver = HtmlUnitDriver(true) open val driver: WebDriver = HtmlUnitDriver(true)
test fun homePage(): Unit { @test fun homePage(): Unit {
driver.get("file://" + File("sample.html").getCanonicalPath()) driver.get("file://" + File("sample.html").getCanonicalPath())
Thread.sleep(1000) Thread.sleep(1000)
@@ -10,7 +10,7 @@ import kotlin.test.*
open class SampleTest { open class SampleTest {
open val driver: WebDriver = HtmlUnitDriver(true) open val driver: WebDriver = HtmlUnitDriver(true)
test fun homePage(): Unit { @test fun homePage(): Unit {
driver.get("file://" + File("sample.html").getCanonicalPath()) driver.get("file://" + File("sample.html").getCanonicalPath())
Thread.sleep(1000) Thread.sleep(1000)
@@ -5,7 +5,8 @@ import sample.Hello
import org.junit.Test import org.junit.Test
class SampleTest { class SampleTest {
Test fun dummy(): Unit { @Test
fun dummy(): Unit {
Hello().doSomething() Hello().doSomething()
} }
} }
@@ -7,7 +7,7 @@ import java.text.NumberFormat
import java.text.DateFormat import java.text.DateFormat
import java.util.Date import java.util.Date
deprecated("This class is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This class is part of an experimental implementation of string templates and is going to be removed")
public class StringTemplate(private val values: Array<Any?>) { public class StringTemplate(private val values: Array<Any?>) {
/** /**
@@ -36,7 +36,7 @@ public class StringTemplate(private val values: Array<Any?>) {
* *
* See [[HtmlFormatter] and [[LocaleFormatter] respectively. * See [[HtmlFormatter] and [[LocaleFormatter] respectively.
*/ */
deprecated("This function is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This function is part of an experimental implementation of string templates and is going to be removed")
public 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)
@@ -47,7 +47,7 @@ public 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
*/ */
deprecated("This function is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This function is part of an experimental implementation of string templates and is going to be removed")
public 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 {
@@ -69,13 +69,13 @@ public 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]]
*/ */
deprecated("This function is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This function is part of an experimental implementation of string templates and is going to be removed")
public 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
*/ */
deprecated("This function is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This function is part of an experimental implementation of string templates and is going to be removed")
public fun StringTemplate.toHtml(formatter: HtmlFormatter = HtmlFormatter()): String = toString(formatter) public fun StringTemplate.toHtml(formatter: HtmlFormatter = HtmlFormatter()): String = toString(formatter)
/** /**
@@ -83,7 +83,7 @@ public fun StringTemplate.toHtml(formatter: HtmlFormatter = HtmlFormatter()): St
* 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]
*/ */
deprecated("This interface is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This interface is part of an experimental implementation of string templates and is going to be removed")
public interface Formatter { public interface Formatter {
public fun format(buffer: Appendable, value: Any?): Unit public fun format(buffer: Appendable, value: Any?): Unit
} }
@@ -92,7 +92,7 @@ public interface Formatter {
* 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
*/ */
deprecated("This class is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This class is part of an experimental implementation of string templates and is going to be removed")
public open class ToStringFormatter : Formatter { public open class ToStringFormatter : Formatter {
private val nullString: String = "null" private val nullString: String = "null"
@@ -118,13 +118,13 @@ public open class ToStringFormatter : Formatter {
} }
} }
deprecated("This property is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This property is part of an experimental implementation of string templates and is going to be removed")
public val defaultLocale: Locale = Locale.getDefault() public val defaultLocale: Locale = Locale.getDefault()
/** /**
* Formats values using a given [[Locale]] for internationalisation * Formats values using a given [[Locale]] for internationalisation
*/ */
deprecated("This class is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This class is part of an experimental implementation of string templates and is going to be removed")
public open class LocaleFormatter(protected val locale: Locale = defaultLocale) : ToStringFormatter() { public open class LocaleFormatter(protected val locale: Locale = defaultLocale) : ToStringFormatter() {
override fun toString(): String = "LocaleFormatter{$locale}" override fun toString(): String = "LocaleFormatter{$locale}"
@@ -155,7 +155,7 @@ public open class LocaleFormatter(protected val locale: Locale = defaultLocale)
/** /**
* Formats values for HTML encoding, escaping special characters in HTML. * Formats values for HTML encoding, escaping special characters in HTML.
*/ */
deprecated("This class is part of an experimental implementation of string templates and is going to be removed") @Deprecated("This class is part of an experimental implementation of string templates and is going to be removed")
public class HtmlFormatter(locale: Locale = defaultLocale) : LocaleFormatter(locale) { public class HtmlFormatter(locale: Locale = defaultLocale) : LocaleFormatter(locale) {
override fun toString(): String = "HtmlFormatter{$locale}" override fun toString(): String = "HtmlFormatter{$locale}"
@@ -9,7 +9,7 @@ import test.kotlin.jdbc.*
class JdbcTemplateTest { class JdbcTemplateTest {
//val dataSource = createDataSource() //val dataSource = createDataSource()
test fun templateInsert() { @test fun templateInsert() {
val id = 3 val id = 3
val name = "Stepan" val name = "Stepan"
@@ -23,7 +23,7 @@ fun createDataSource() : DataSource {
} }
class JdbcTest { class JdbcTest {
test fun queryWithIndexColumnAccess() { @test fun queryWithIndexColumnAccess() {
dataSource.query("select * from foo") { dataSource.query("select * from foo") {
for (row in it) { for (row in it) {
println("id ${row[1]} and name: ${row[2]}") println("id ${row[1]} and name: ${row[2]}")
@@ -31,7 +31,7 @@ class JdbcTest {
} }
} }
test fun queryWithNamedColumnAccess() { @test fun queryWithNamedColumnAccess() {
// query using names // query using names
dataSource.query("select * from foo") { dataSource.query("select * from foo") {
for (row in it) { for (row in it) {
@@ -40,7 +40,7 @@ class JdbcTest {
} }
} }
test fun getValuesAsMap() { @test fun getValuesAsMap() {
dataSource.query("select * from foo") { dataSource.query("select * from foo") {
for (row in it) { for (row in it) {
println(row.getValuesAsMap()) println(row.getValuesAsMap())
@@ -48,7 +48,7 @@ class JdbcTest {
} }
} }
test fun stringFormat() { @test fun stringFormat() {
dataSource.query(kotlin.template.StringTemplate(arrayOf("select * from foo where id = ", 1))) { dataSource.query(kotlin.template.StringTemplate(arrayOf("select * from foo where id = ", 1))) {
for (row in it) { for (row in it) {
println(row.getValuesAsMap()) println(row.getValuesAsMap())
@@ -56,7 +56,7 @@ class JdbcTest {
} }
} }
test fun mapIterator() { @test fun mapIterator() {
val mapper = { rs: ResultSet -> val mapper = { rs: ResultSet ->
"id: ${rs["id"]}" "id: ${rs["id"]}"
} }
@@ -68,7 +68,7 @@ class JdbcTest {
} }
} }
test fun map() { @test fun map() {
dataSource.query("select * from foo") { dataSource.query("select * from foo") {
val rows = it.map { "id: ${it["id"]}" } val rows = it.map { "id: ${it["id"]}" }
for (row in rows) { for (row in rows) {
@@ -77,13 +77,13 @@ class JdbcTest {
} }
} }
test fun count() { @test fun count() {
dataSource.query("select count(*) from foo") { dataSource.query("select count(*) from foo") {
println("count: ${it.singleInt()}") println("count: ${it.singleInt()}")
} }
} }
test fun formatCursor() { @test fun formatCursor() {
dataSource.query("select * from foo") { dataSource.query("select * from foo") {
println(it.getColumnNames().toList().joinToString("\t")) println(it.getColumnNames().toList().joinToString("\t"))
@@ -266,7 +266,7 @@ public fun ShortArray.copyOf(): ShortArray {
/** /**
* Returns new array which is a copy of the original array. * Returns new array which is a copy of the original array.
*/ */
platformName("mutableCopyOf") @JvmName("mutableCopyOf")
public fun <T> Array<T>.copyOf(): Array<T> { public fun <T> Array<T>.copyOf(): Array<T> {
return Arrays.copyOf(this, size()) return Arrays.copyOf(this, size())
} }
@@ -408,7 +408,7 @@ public fun ShortArray.copyOfRange(fromIndex: Int, toIndex: Int): ShortArray {
/** /**
* Returns new array which is a copy of range of original array. * Returns new array which is a copy of range of original array.
*/ */
platformName("mutableCopyOfRange") @JvmName("mutableCopyOfRange")
public fun <T> Array<T>.copyOfRange(fromIndex: Int, toIndex: Int): Array<T> { public fun <T> Array<T>.copyOfRange(fromIndex: Int, toIndex: Int): Array<T> {
return Arrays.copyOfRange(this, fromIndex, toIndex) return Arrays.copyOfRange(this, fromIndex, toIndex)
} }
@@ -56,7 +56,7 @@ import kotlin.jvm.internal.Intrinsic
/** /**
* Creates an input stream for reading data from this byte array. * Creates an input stream for reading data from this byte array.
*/ */
deprecated("Use inputStream() method instead.", ReplaceWith("this.inputStream()")) @Deprecated("Use inputStream() method instead.", ReplaceWith("this.inputStream()"))
public val ByteArray.inputStream : ByteArrayInputStream public val ByteArray.inputStream : ByteArrayInputStream
get() = inputStream() get() = inputStream()
@@ -1,7 +1,7 @@
package kotlin package kotlin
deprecated("This exception is no longer thrown by any standard library classes and is going to be removed") @Deprecated("This exception is no longer thrown by any standard library classes and is going to be removed")
public class EmptyIterableException(private val it: Iterable<*>) : RuntimeException("$it is empty") public class EmptyIterableException(private val it: Iterable<*>) : RuntimeException("$it is empty")
deprecated("This exception is no longer thrown by any standard library classes and is going to be removed") @Deprecated("This exception is no longer thrown by any standard library classes and is going to be removed")
public class DuplicateKeyException(message : String = "Duplicate keys detected") : RuntimeException(message) public class DuplicateKeyException(message : String = "Duplicate keys detected") : RuntimeException(message)
@@ -100,7 +100,7 @@ public val Collection<*>.indices: IntRange
/** /**
* Returns an [IntRange] that starts with zero and ends at the value of this number but does not include it. * Returns an [IntRange] that starts with zero and ends at the value of this number but does not include it.
*/ */
deprecated("Use 0..n-1 range instead.", ReplaceWith("0..this - 1")) @Deprecated("Use 0..n-1 range instead.", ReplaceWith("0..this - 1"))
public val Int.indices: IntRange public val Int.indices: IntRange
get() = 0..this - 1 get() = 0..this - 1
@@ -217,7 +217,7 @@ public fun <T> List<T>.binarySearch(element: T, comparator: Comparator<in T>, fr
* *
* If the list contains multiple elements with the specified [key], there is no guarantee which one will be found. * If the list contains multiple elements with the specified [key], there is no guarantee which one will be found.
*/ */
public inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size(), inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> K?): Int = public inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size(), crossinline selector: (T) -> K?): Int =
binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) } binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) }
// do not introduce this overload --- too rare // do not introduce this overload --- too rare
@@ -37,7 +37,7 @@ public fun <K, V> Map<K, V>.withDefault(default: (key: K) -> V): Map<K, V> =
* *
* When this map already have an implicit default value provided with a former call to [withDefault], it is being replaced by this call. * When this map already have an implicit default value provided with a former call to [withDefault], it is being replaced by this call.
*/ */
platformName("withDefaultMutable") @platformName("withDefaultMutable")
public fun <K, V> MutableMap<K, V>.withDefault(default: (key: K) -> V): MutableMap<K, V> = public fun <K, V> MutableMap<K, V>.withDefault(default: (key: K) -> V): MutableMap<K, V> =
when (this) { when (this) {
is MutableMapWithDefault -> this.map.withDefault(default) is MutableMapWithDefault -> this.map.withDefault(default)
@@ -17,7 +17,7 @@ public fun <K, V> MutableMap<K, V>.set(key: K, value: V): V? = put(key, value)
* getOrPut is not supported on [ConcurrentMap] since it cannot be implemented correctly in terms of concurrency. * getOrPut is not supported on [ConcurrentMap] since it cannot be implemented correctly in terms of concurrency.
* Use [concurrentGetOrPut] instead, or cast this to a [MutableMap] if you want to sacrifice the concurrent-safety. * Use [concurrentGetOrPut] instead, or cast this to a [MutableMap] if you want to sacrifice the concurrent-safety.
*/ */
deprecated("Use concurrentGetOrPut instead or cast this map to MutableMap.") @Deprecated("Use concurrentGetOrPut instead or cast this map to MutableMap.")
public inline fun <K, V> ConcurrentMap<K, V>.getOrPut(key: K, defaultValue: () -> V): Nothing = public inline fun <K, V> ConcurrentMap<K, V>.getOrPut(key: K, defaultValue: () -> V): Nothing =
throw UnsupportedOperationException("getOrPut is not supported on ConcurrentMap.") throw UnsupportedOperationException("getOrPut is not supported on ConcurrentMap.")
@@ -1,7 +1,6 @@
package kotlin package kotlin
import java.util.ArrayList import java.util.ArrayList
import kotlin.platform.platformName
/** /**
* Returns a single list of all elements from all collections in the given collection. * Returns a single list of all elements from all collections in the given collection.
@@ -47,6 +47,6 @@ public fun <T> List<T>.asReversed(): List<T> = ReversedListReadOnly(this)
* Returns a reversed mutable view of the original mutable List. * Returns a reversed mutable view of the original mutable List.
* All changes made in the original list will be reflected in the reversed one and vice versa. * All changes made in the original list will be reflected in the reversed one and vice versa.
*/ */
platformName("asReversedMutable") @platformName("asReversedMutable")
public fun <T> MutableList<T>.asReversed(): MutableList<T> = ReversedList(this) public fun <T> MutableList<T>.asReversed(): MutableList<T> = ReversedList(this)
@@ -26,7 +26,7 @@ public fun <T> Iterator<T>.asSequence(): Sequence<T> {
return iteratorSequence.constrainOnce() return iteratorSequence.constrainOnce()
} }
deprecated("Use asSequence() instead.", ReplaceWith("asSequence()")) @Deprecated("Use asSequence() instead.", ReplaceWith("asSequence()"))
public fun <T> Iterator<T>.sequence(): Sequence<T> = asSequence() public fun <T> Iterator<T>.sequence(): Sequence<T> = asSequence()
@@ -58,7 +58,7 @@ public inline fun <T> ReentrantReadWriteLock.write(action: () -> T): T {
* *
* @return the return value of the action. * @return the return value of the action.
*/ */
deprecated("Use CountDownLatch(Int) instead and await it manually.") @Deprecated("Use CountDownLatch(Int) instead and await it manually.")
public fun <T> Int.latch(operation: CountDownLatch.() -> T): T { public fun <T> Int.latch(operation: CountDownLatch.() -> T): T {
val latch = CountDownLatch(this) val latch = CountDownLatch(this)
val result = latch.operation() val result = latch.operation()
@@ -12,7 +12,7 @@ public val currentThread: Thread
* Exposes the name of this thread as a property. * Exposes the name of this thread as a property.
*/ */
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("name")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("name"))
public var Thread.name: String public var Thread.name: String
get() = getName() get() = getName()
set(value) { set(value) {
@@ -23,7 +23,7 @@ public var Thread.name: String
* Exposes the daemon flag of this thread as a property. * Exposes the daemon flag of this thread as a property.
* The Java Virtual Machine exits when the only threads running are all daemon threads. * The Java Virtual Machine exits when the only threads running are all daemon threads.
*/ */
deprecated("Use synthetic extension property isDaemon instead.", ReplaceWith("this.isDaemon")) @Deprecated("Use synthetic extension property isDaemon instead.", ReplaceWith("this.isDaemon"))
public var Thread.daemon: Boolean public var Thread.daemon: Boolean
get() = isDaemon() get() = isDaemon()
set(value) { set(value) {
@@ -33,7 +33,7 @@ public var Thread.daemon: Boolean
/** /**
* Exposes the alive state of this thread as a property. * Exposes the alive state of this thread as a property.
*/ */
deprecated("Use synthetic extension property isAlive instead.", ReplaceWith("this.isAlive")) @Deprecated("Use synthetic extension property isAlive instead.", ReplaceWith("this.isAlive"))
public val Thread.alive: Boolean public val Thread.alive: Boolean
get() = isAlive() get() = isAlive()
@@ -41,7 +41,7 @@ public val Thread.alive: Boolean
* Exposes the priority of this thread as a property. * Exposes the priority of this thread as a property.
*/ */
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("priority")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("priority"))
public var Thread.priority: Int public var Thread.priority: Int
get() = getPriority() get() = getPriority()
set(value) { set(value) {
@@ -52,7 +52,7 @@ public var Thread.priority: Int
* Exposes the context class loader of this thread as a property. * Exposes the context class loader of this thread as a property.
*/ */
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("contextClassLoader")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("contextClassLoader"))
public var Thread.contextClassLoader: ClassLoader? public var Thread.contextClassLoader: ClassLoader?
get() = getContextClassLoader() get() = getContextClassLoader()
set(value) { set(value) {
@@ -108,7 +108,7 @@ public inline fun <T: Any> ThreadLocal<T>.getOrSet(default: () -> T): T {
* Allows you to use the executor as a function to * Allows you to use the executor as a function to
* execute the given block on the [Executor]. * execute the given block on the [Executor].
*/ */
deprecated("Use Executor.execute(Runnable) instead.") // do not specify ReplaceWith("execute(action)") due to KT-8597 @Deprecated("Use Executor.execute(Runnable) instead.") // do not specify ReplaceWith("execute(action)") due to KT-8597
public fun Executor.invoke(action: () -> Unit) { public fun Executor.invoke(action: () -> Unit) {
execute(action) execute(action)
} }
@@ -117,7 +117,7 @@ public fun Executor.invoke(action: () -> Unit) {
* Allows you to use the executor service as a function to * Allows you to use the executor service as a function to
* execute the given block on the [ExecutorService]. * execute the given block on the [ExecutorService].
*/ */
deprecated("Use ExecutorService.submit(Callable) instead.") // do not specify ReplaceWith("submit(action)") due to KT-8597 @Deprecated("Use ExecutorService.submit(Callable) instead.") // do not specify ReplaceWith("submit(action)") due to KT-8597
public fun <T> ExecutorService.invoke(action: () -> T): Future<T> { public fun <T> ExecutorService.invoke(action: () -> T): Future<T> {
return submit(action) return submit(action)
} }
@@ -2,105 +2,105 @@ package kotlin
import java.util.* import java.util.*
deprecated("Use listOf(...) or arrayListOf(...) instead", ReplaceWith("arrayListOf(*values)")) @Deprecated("Use listOf(...) or arrayListOf(...) instead", ReplaceWith("arrayListOf(*values)"))
public fun arrayList<T>(vararg values: T): ArrayList<T> = arrayListOf(*values) public fun arrayList<T>(vararg values: T): ArrayList<T> = arrayListOf(*values)
deprecated("Use setOf(...) or hashSetOf(...) instead", ReplaceWith("hashSetOf(*values)")) @Deprecated("Use setOf(...) or hashSetOf(...) instead", ReplaceWith("hashSetOf(*values)"))
public fun hashSet<T>(vararg values: T): HashSet<T> = hashSetOf(*values) public fun hashSet<T>(vararg values: T): HashSet<T> = hashSetOf(*values)
deprecated("Use mapOf(...) or hashMapOf(...) instead", ReplaceWith("hashMapOf(*values)")) @Deprecated("Use mapOf(...) or hashMapOf(...) instead", ReplaceWith("hashMapOf(*values)"))
public fun <K, V> hashMap(vararg values: Pair<K, V>): HashMap<K, V> = hashMapOf(*values) public fun <K, V> hashMap(vararg values: Pair<K, V>): HashMap<K, V> = hashMapOf(*values)
deprecated("Use listOf(...) or linkedListOf(...) instead", ReplaceWith("linkedListOf(*values)")) @Deprecated("Use listOf(...) or linkedListOf(...) instead", ReplaceWith("linkedListOf(*values)"))
public fun linkedList<T>(vararg values: T): LinkedList<T> = linkedListOf(*values) public fun linkedList<T>(vararg values: T): LinkedList<T> = linkedListOf(*values)
deprecated("Use linkedMapOf(...) instead", ReplaceWith("linkedMapOf(*values)")) @Deprecated("Use linkedMapOf(...) instead", ReplaceWith("linkedMapOf(*values)"))
public fun <K, V> linkedMap(vararg values: Pair<K, V>): LinkedHashMap<K, V> = linkedMapOf(*values) public fun <K, V> linkedMap(vararg values: Pair<K, V>): LinkedHashMap<K, V> = linkedMapOf(*values)
/** Copies all characters into a [[Collection] */ /** Copies all characters into a [[Collection] */
deprecated("Use toList() instead.", ReplaceWith("toList()")) @Deprecated("Use toList() instead.", ReplaceWith("toList()"))
public fun String.toCollection(): Collection<Char> = toCollection(ArrayList<Char>(this.length())) public fun String.toCollection(): Collection<Char> = toCollection(ArrayList<Char>(this.length()))
/** /**
* A helper method for creating a [[Runnable]] from a function * A helper method for creating a [[Runnable]] from a function
*/ */
deprecated("Use SAM constructor: Runnable(...)", ReplaceWith("Runnable(action)")) @Deprecated("Use SAM constructor: Runnable(...)", ReplaceWith("Runnable(action)"))
public /*inline*/ fun runnable(action: () -> Unit): Runnable = Runnable(action) public /*inline*/ fun runnable(action: () -> Unit): Runnable = Runnable(action)
deprecated("Use forEachIndexed instead.", ReplaceWith("forEachIndexed(operation)")) @Deprecated("Use forEachIndexed instead.", ReplaceWith("forEachIndexed(operation)"))
public inline fun <T> List<T>.forEachWithIndex(operation: (Int, T) -> Unit): Unit = forEachIndexed(operation) public inline fun <T> List<T>.forEachWithIndex(operation: (Int, T) -> Unit): Unit = forEachIndexed(operation)
deprecated("Function with undefined semantic") @Deprecated("Function with undefined semantic")
public fun <T> countTo(n: Int): (T) -> Boolean { public fun <T> countTo(n: Int): (T) -> Boolean {
var count = 0 var count = 0
return { ++count; count <= n } return { ++count; count <= n }
} }
deprecated("Use contains() function instead", ReplaceWith("contains(item)")) @Deprecated("Use contains() function instead", ReplaceWith("contains(item)"))
public fun <T> Iterable<T>.containsItem(item : T) : Boolean = contains(item) public fun <T> Iterable<T>.containsItem(item : T) : Boolean = contains(item)
deprecated("Use sortBy() instead", ReplaceWith("sortedWith(comparator)")) @Deprecated("Use sortBy() instead", ReplaceWith("sortedWith(comparator)"))
public fun <T> Iterable<T>.sort(comparator: java.util.Comparator<T>) : List<T> = sortedWith(comparator) public fun <T> Iterable<T>.sort(comparator: java.util.Comparator<T>) : List<T> = sortedWith(comparator)
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val Array<*>.size: Int get() = size() public val Array<*>.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val ByteArray.size: Int get() = size() public val ByteArray.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val CharArray.size: Int get() = size() public val CharArray.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val ShortArray.size: Int get() = size() public val ShortArray.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val IntArray.size: Int get() = size() public val IntArray.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val LongArray.size: Int get() = size() public val LongArray.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val FloatArray.size: Int get() = size() public val FloatArray.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val DoubleArray.size: Int get() = size() public val DoubleArray.size: Int get() = size()
deprecated("Use size() instead", ReplaceWith("size()")) @Deprecated("Use size() instead", ReplaceWith("size()"))
public val BooleanArray.size: Int get() = size() public val BooleanArray.size: Int get() = size()
deprecated("Use compareValuesBy() instead", ReplaceWith("compareValuesBy(a, b, *functions)")) @Deprecated("Use compareValuesBy() instead", ReplaceWith("compareValuesBy(a, b, *functions)"))
public fun <T : Any> compareBy(a: T?, b: T?, vararg functions: (T) -> Comparable<*>?): Int = compareValuesBy(a, b, *functions) public fun <T : Any> compareBy(a: T?, b: T?, vararg functions: (T) -> Comparable<*>?): Int = compareValuesBy(a, b, *functions)
/** Returns true if this collection is empty */ /** Returns true if this collection is empty */
deprecated("Use isEmpty() function call instead", ReplaceWith("isEmpty()")) @Deprecated("Use isEmpty() function call instead", ReplaceWith("isEmpty()"))
public val Collection<*>.empty: Boolean public val Collection<*>.empty: Boolean
get() = isEmpty() get() = isEmpty()
/** Returns the size of the collection */ /** Returns the size of the collection */
deprecated("Use size() function call instead", ReplaceWith("size()")) @Deprecated("Use size() function call instead", ReplaceWith("size()"))
public val Collection<*>.size: Int public val Collection<*>.size: Int
get() = size() get() = size()
/** Returns the size of the map */ /** Returns the size of the map */
deprecated("Use size() function call instead", ReplaceWith("size()")) @Deprecated("Use size() function call instead", ReplaceWith("size()"))
public val Map<*, *>.size: Int public val Map<*, *>.size: Int
get() = size() get() = size()
/** Returns true if this map is empty */ /** Returns true if this map is empty */
deprecated("Use isEmpty() function call instead", ReplaceWith("isEmpty()")) @Deprecated("Use isEmpty() function call instead", ReplaceWith("isEmpty()"))
public val Map<*, *>.empty: Boolean public val Map<*, *>.empty: Boolean
get() = isEmpty() get() = isEmpty()
/** Returns true if this collection is not empty */ /** Returns true if this collection is not empty */
deprecated("Use isNotEmpty() function call instead", ReplaceWith("isNotEmpty()")) @Deprecated("Use isNotEmpty() function call instead", ReplaceWith("isNotEmpty()"))
public val Collection<*>.notEmpty: Boolean public val Collection<*>.notEmpty: Boolean
get() = isNotEmpty() get() = isNotEmpty()
deprecated("Use length() instead", ReplaceWith("length()")) @Deprecated("Use length() instead", ReplaceWith("length()"))
public val CharSequence.length: Int public val CharSequence.length: Int
get() = length() get() = length()
@@ -2,40 +2,40 @@ package kotlin
// deprecated to be removed after M12 // deprecated to be removed after M12
deprecated("Use arrayOf() instead.", ReplaceWith("arrayOf(*t)")) @Deprecated("Use arrayOf() instead.", ReplaceWith("arrayOf(*t)"))
inline public fun <reified T> array(vararg t : T) : Array<T> = arrayOf(*t) inline public fun <reified T> array(vararg t : T) : Array<T> = arrayOf(*t)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use doubleArrayOf() instead.", ReplaceWith("doubleArrayOf(*content)")) @Deprecated("Use doubleArrayOf() instead.", ReplaceWith("doubleArrayOf(*content)"))
inline public fun doubleArray(vararg content : Double) : DoubleArray = doubleArrayOf(*content) inline public fun doubleArray(vararg content : Double) : DoubleArray = doubleArrayOf(*content)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use floatArrayOf() instead.", ReplaceWith("floatArrayOf(*content)")) @Deprecated("Use floatArrayOf() instead.", ReplaceWith("floatArrayOf(*content)"))
inline public fun floatArray(vararg content : Float) : FloatArray = floatArrayOf(*content) inline public fun floatArray(vararg content : Float) : FloatArray = floatArrayOf(*content)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use longArrayOf() instead.", ReplaceWith("longArrayOf(*content)")) @Deprecated("Use longArrayOf() instead.", ReplaceWith("longArrayOf(*content)"))
inline public fun longArray(vararg content : Long) : LongArray = longArrayOf(*content) inline public fun longArray(vararg content : Long) : LongArray = longArrayOf(*content)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use intArrayOf() instead.", ReplaceWith("intArrayOf(*content)")) @Deprecated("Use intArrayOf() instead.", ReplaceWith("intArrayOf(*content)"))
inline public fun intArray(vararg content : Int) : IntArray = intArrayOf(*content) inline public fun intArray(vararg content : Int) : IntArray = intArrayOf(*content)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use charArrayOf() instead.", ReplaceWith("charArrayOf(*content)")) @Deprecated("Use charArrayOf() instead.", ReplaceWith("charArrayOf(*content)"))
inline public fun charArray(vararg content : Char) : CharArray = charArrayOf(*content) inline public fun charArray(vararg content : Char) : CharArray = charArrayOf(*content)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use shortArrayOf() instead.", ReplaceWith("shortArrayOf(*content)")) @Deprecated("Use shortArrayOf() instead.", ReplaceWith("shortArrayOf(*content)"))
inline public fun shortArray(vararg content : Short) : ShortArray = shortArrayOf(*content) inline public fun shortArray(vararg content : Short) : ShortArray = shortArrayOf(*content)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use byteArrayOf() instead.", ReplaceWith("byteArrayOf(*content)")) @Deprecated("Use byteArrayOf() instead.", ReplaceWith("byteArrayOf(*content)"))
inline public fun byteArray(vararg content : Byte) : ByteArray = byteArrayOf(*content) inline public fun byteArray(vararg content : Byte) : ByteArray = byteArrayOf(*content)
suppress("NOTHING_TO_INLINE") @Suppress("NOTHING_TO_INLINE")
deprecated("Use booleanArrayOf() instead.", ReplaceWith("booleanArrayOf(*content)")) @Deprecated("Use booleanArrayOf() instead.", ReplaceWith("booleanArrayOf(*content)"))
inline public fun booleanArray(vararg content : Boolean) : BooleanArray = booleanArrayOf(*content) inline public fun booleanArray(vararg content : Boolean) : BooleanArray = booleanArrayOf(*content)
deprecated("Use toTypedArray() instead.", ReplaceWith("toTypedArray()")) @Deprecated("Use toTypedArray() instead.", ReplaceWith("toTypedArray()"))
inline public fun <reified T> Collection<T>.copyToArray(): Array<T> = toTypedArray() inline public fun <reified T> Collection<T>.copyToArray(): Array<T> = toTypedArray()
@@ -19,26 +19,26 @@ package kotlin
import java.util.* import java.util.*
import java.util.concurrent.Callable import java.util.concurrent.Callable
deprecated("Use sortedSetOf(...) instead", ReplaceWith("sortedSetOf(*values)")) @Deprecated("Use sortedSetOf(...) instead", ReplaceWith("sortedSetOf(*values)"))
public fun sortedSet<T>(vararg values: T): TreeSet<T> = sortedSetOf(*values) public fun sortedSet<T>(vararg values: T): TreeSet<T> = sortedSetOf(*values)
deprecated("Use sortedSetOf(...) instead", ReplaceWith("sortedSetOf(comparator, *values)")) @Deprecated("Use sortedSetOf(...) instead", ReplaceWith("sortedSetOf(comparator, *values)"))
public fun sortedSet<T>(comparator: Comparator<T>, vararg values: T): TreeSet<T> = sortedSetOf(comparator, *values) public fun sortedSet<T>(comparator: Comparator<T>, vararg values: T): TreeSet<T> = sortedSetOf(comparator, *values)
deprecated("Use sortedMapOf(...) instead", ReplaceWith("sortedMapOf(*values)")) @Deprecated("Use sortedMapOf(...) instead", ReplaceWith("sortedMapOf(*values)"))
public fun <K, V> sortedMap(vararg values: Pair<K, V>): SortedMap<K, V> = sortedMapOf(*values) public fun <K, V> sortedMap(vararg values: Pair<K, V>): SortedMap<K, V> = sortedMapOf(*values)
/** /**
* A helper method for creating a [[Callable]] from a function * A helper method for creating a [[Callable]] from a function
*/ */
deprecated("Use SAM constructor: Callable(...)", ReplaceWith("Callable(action)", "java.util.concurrent.Callable")) @Deprecated("Use SAM constructor: Callable(...)", ReplaceWith("Callable(action)", "java.util.concurrent.Callable"))
public /*inline*/ fun <T> callable(action: () -> T): Callable<T> = Callable(action) public /*inline*/ fun <T> callable(action: () -> T): Callable<T> = Callable(action)
deprecated("Use length() instead", ReplaceWith("length()")) @Deprecated("Use length() instead", ReplaceWith("length()"))
public val String.size: Int public val String.size: Int
get() = length() get() = length()
deprecated("Use length() instead", ReplaceWith("length()")) @Deprecated("Use length() instead", ReplaceWith("length()"))
public val CharSequence.size: Int public val CharSequence.size: Int
get() = length() get() = length()
@@ -1,113 +1,113 @@
package kotlin package kotlin
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun <T> Array<out T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun <T> Array<out T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun BooleanArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun BooleanArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun ByteArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun ByteArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun CharArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun CharArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun DoubleArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun DoubleArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun FloatArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun FloatArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun IntArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun IntArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun LongArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun LongArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun ShortArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun ShortArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun <T> Iterable<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun <T> Iterable<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinToString() instead", ReplaceWith("joinToString(separator, prefix, postfix, limit, truncated)"))
public fun <T> Sequence<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { public fun <T> Sequence<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated) return joinToString(separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun <T> Array<out T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun <T> Array<out T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun BooleanArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun BooleanArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun ByteArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun ByteArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun CharArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun CharArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun DoubleArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun DoubleArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun FloatArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun FloatArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun IntArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun IntArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun LongArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun LongArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun ShortArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun ShortArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun <T> Iterable<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun <T> Iterable<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)")) @Deprecated("Use joinTo() instead", ReplaceWith("joinTo(buffer, separator, prefix, postfix, limit, truncated)"))
public fun <T> Sequence<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { public fun <T> Sequence<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated) joinTo(buffer, separator, prefix, postfix, limit, truncated)
} }
+4 -4
View File
@@ -10,14 +10,14 @@ import java.lang.IndexOutOfBoundsException
// Properties // Properties
deprecated("use textContent directly instead") @Deprecated("use textContent directly instead")
public var Node.text: String public var Node.text: String
get() = textContent ?: "" get() = textContent ?: ""
set(value) { set(value) {
textContent = value textContent = value
} }
deprecated("You shouldn't use it as setter will drop all elements and get may return not exactly content user can expect") @Deprecated("You shouldn't use it as setter will drop all elements and get may return not exactly content user can expect")
public var Element.childrenText: String public var Element.childrenText: String
get() { get() {
val buffer = StringBuilder() val buffer = StringBuilder()
@@ -101,7 +101,7 @@ public fun Document?.elements(namespaceUri: String, localName: String): List<Ele
} }
public fun NodeList?.asList() : List<Node> = if (this == null) emptyList() else NodeListAsList(this) public fun NodeList?.asList() : List<Node> = if (this == null) emptyList() else NodeListAsList(this)
deprecated("use asList instead", ReplaceWith("asList()")) @Deprecated("use asList instead", ReplaceWith("asList()"))
public fun NodeList?.toList(): List<Node> = asList() public fun NodeList?.toList(): List<Node> = asList()
public fun NodeList?.toElementList(): List<Element> { public fun NodeList?.toElementList(): List<Element> {
@@ -268,7 +268,7 @@ private class PreviousSiblings(private var node: Node) : Iterable<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 */
deprecated("use property isText instead", ReplaceWith("isText")) @Deprecated("use property isText instead", ReplaceWith("isText"))
public fun Node.isText() : Boolean = isText public fun Node.isText() : Boolean = isText
/** /**
+15 -15
View File
@@ -6,12 +6,12 @@ import org.w3c.dom.events.MouseEvent
// JavaScript style properties for JVM : TODO could auto-generate these // JavaScript style properties for JVM : TODO could auto-generate these
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("bubbles")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("bubbles"))
public val Event.bubbles: Boolean public val Event.bubbles: Boolean
get() = getBubbles() get() = getBubbles()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("cancelable")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("cancelable"))
public val Event.cancelable: Boolean public val Event.cancelable: Boolean
get() = getCancelable() get() = getCancelable()
@@ -19,17 +19,17 @@ public val Event.getCurrentTarget: EventTarget?
get() = getCurrentTarget() get() = getCurrentTarget()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("eventPhase")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("eventPhase"))
public val Event.eventPhase: Short public val Event.eventPhase: Short
get() = getEventPhase() get() = getEventPhase()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("target")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("target"))
public val Event.target: EventTarget? public val Event.target: EventTarget?
get() = getTarget() get() = getTarget()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("timeStamp")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("timeStamp"))
public val Event.timeStamp: Long public val Event.timeStamp: Long
get() = getTimeStamp() get() = getTimeStamp()
@@ -39,51 +39,51 @@ public val Event.eventType: String
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("altKey")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("altKey"))
public val MouseEvent.altKey: Boolean public val MouseEvent.altKey: Boolean
get() = getAltKey() get() = getAltKey()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("button")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("button"))
public val MouseEvent.button: Short public val MouseEvent.button: Short
get() = getButton() get() = getButton()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("clientX")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("clientX"))
public val MouseEvent.clientX: Int public val MouseEvent.clientX: Int
get() = getClientX() get() = getClientX()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("clientY")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("clientY"))
public val MouseEvent.clientY: Int public val MouseEvent.clientY: Int
get() = getClientY() get() = getClientY()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("ctrlKey")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("ctrlKey"))
public val MouseEvent.ctrlKey: Boolean public val MouseEvent.ctrlKey: Boolean
get() = getCtrlKey() get() = getCtrlKey()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("metaKey")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("metaKey"))
public val MouseEvent.metaKey: Boolean public val MouseEvent.metaKey: Boolean
get() = getMetaKey() get() = getMetaKey()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("relatedTarget")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("relatedTarget"))
public val MouseEvent.relatedTarget: EventTarget? public val MouseEvent.relatedTarget: EventTarget?
get() = getRelatedTarget() get() = getRelatedTarget()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("screenX")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("screenX"))
public val MouseEvent.screenX: Int public val MouseEvent.screenX: Int
get() = getScreenX() get() = getScreenX()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("screenY")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("screenY"))
public val MouseEvent.screenY: Int public val MouseEvent.screenY: Int
get() = getScreenY() get() = getScreenY()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("shiftKey")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("shiftKey"))
public val MouseEvent.shiftKey: Boolean public val MouseEvent.shiftKey: Boolean
get() = getShiftKey() get() = getShiftKey()
+23 -23
View File
@@ -20,80 +20,80 @@ import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult import javax.xml.transform.stream.StreamResult
// JavaScript style properties - TODO could auto-generate these // JavaScript style properties - TODO could auto-generate these
@deprecated("Use getNodeName()", ReplaceWith("getNodeName() ?: \"\"")) @Deprecated("Use getNodeName()", ReplaceWith("getNodeName() ?: \"\""))
public val Node.nodeName: String public val Node.nodeName: String
get() = getNodeName() ?: "" get() = getNodeName() ?: ""
@deprecated("Use getNodeValue()", ReplaceWith("getNodeValue() ?: \"\"")) @Deprecated("Use getNodeValue()", ReplaceWith("getNodeValue() ?: \"\""))
public val Node.nodeValue: String public val Node.nodeValue: String
get() = getNodeValue() ?: "" get() = getNodeValue() ?: ""
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("nodeType")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("nodeType"))
public val Node.nodeType: Short public val Node.nodeType: Short
get() = getNodeType() get() = getNodeType()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("parentNode")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("parentNode"))
public val Node.parentNode: Node? public val Node.parentNode: Node?
get() = getParentNode() get() = getParentNode()
@deprecated("Use getChildNodes()", ReplaceWith("getChildNodes()!!")) @Deprecated("Use getChildNodes()", ReplaceWith("getChildNodes()!!"))
public val Node.childNodes: NodeList public val Node.childNodes: NodeList
get() = getChildNodes()!! get() = getChildNodes()!!
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("firstChild")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("firstChild"))
public val Node.firstChild: Node? public val Node.firstChild: Node?
get() = getFirstChild() get() = getFirstChild()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("lastChild")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("lastChild"))
public val Node.lastChild: Node? public val Node.lastChild: Node?
get() = getLastChild() get() = getLastChild()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("nextSibling")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("nextSibling"))
public val Node.nextSibling: Node? public val Node.nextSibling: Node?
get() = getNextSibling() get() = getNextSibling()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("previousSibling")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("previousSibling"))
public val Node.previousSibling: Node? public val Node.previousSibling: Node?
get() = getPreviousSibling() get() = getPreviousSibling()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("attributes")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("attributes"))
public val Node.attributes: NamedNodeMap? public val Node.attributes: NamedNodeMap?
get() = getAttributes() get() = getAttributes()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("ownerDocument")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("ownerDocument"))
public val Node.ownerDocument: Document? public val Node.ownerDocument: Document?
get() = getOwnerDocument() get() = getOwnerDocument()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("documentElement")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("documentElement"))
public val Document.documentElement: Element? public val Document.documentElement: Element?
get() = this.getDocumentElement() get() = this.getDocumentElement()
@deprecated("Use getNamespaceURI()", ReplaceWith("getNamespaceURI() ?: \"\"")) @Deprecated("Use getNamespaceURI()", ReplaceWith("getNamespaceURI() ?: \"\""))
public val Node.namespaceURI: String public val Node.namespaceURI: String
get() = getNamespaceURI() ?: "" get() = getNamespaceURI() ?: ""
@deprecated("Use getPrefix()", ReplaceWith("getPrefix() ?: \"\"")) @Deprecated("Use getPrefix()", ReplaceWith("getPrefix() ?: \"\""))
public val Node.prefix: String public val Node.prefix: String
get() = getPrefix() ?: "" get() = getPrefix() ?: ""
@deprecated("Use getLocalName()", ReplaceWith("getLocalName() ?: \"\"")) @Deprecated("Use getLocalName()", ReplaceWith("getLocalName() ?: \"\""))
public val Node.localName: String public val Node.localName: String
get() = getLocalName() ?: "" get() = getLocalName() ?: ""
@deprecated("Use getBaseURI", ReplaceWith("getBaseURI() ?: \"\"")) @Deprecated("Use getBaseURI", ReplaceWith("getBaseURI() ?: \"\""))
public val Node.baseURI: String public val Node.baseURI: String
get() = getBaseURI() ?: "" get() = getBaseURI() ?: ""
@deprecated("Use getTextContent()/setTextContent()") @Deprecated("Use getTextContent()/setTextContent()")
public var Node.textContent: String public var Node.textContent: String
get() = getTextContent() ?: "" get() = getTextContent() ?: ""
set(value) { set(value) {
@@ -101,32 +101,32 @@ public var Node.textContent: String
} }
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length"))
public val DOMStringList.length: Int public val DOMStringList.length: Int
get() = this.getLength() get() = this.getLength()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length"))
public val NameList.length: Int public val NameList.length: Int
get() = this.getLength() get() = this.getLength()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length"))
public val DOMImplementationList.length: Int public val DOMImplementationList.length: Int
get() = this.getLength() get() = this.getLength()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length"))
public val NodeList.length: Int public val NodeList.length: Int
get() = this.getLength() get() = this.getLength()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length"))
public val CharacterData.length: Int public val CharacterData.length: Int
get() = this.getLength() get() = this.getLength()
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("length"))
public val NamedNodeMap.length: Int public val NamedNodeMap.length: Int
get() = this.getLength() get() = this.getLength()
+1 -1
View File
@@ -7,7 +7,7 @@ import java.nio.charset.CharsetEncoder
import java.util.NoSuchElementException import java.util.NoSuchElementException
/** Returns an [Iterator] of bytes in this input stream. */ /** Returns an [Iterator] of bytes in this input stream. */
deprecated("It's not recommended to iterate through input stream bytes") @Deprecated("It's not recommended to iterate through input stream bytes")
public fun InputStream.iterator(): ByteIterator = public fun InputStream.iterator(): ByteIterator =
object : ByteIterator() { object : ByteIterator() {
+2 -2
View File
@@ -250,10 +250,10 @@ public inline fun <T> Reader.useLines(block: (Sequence<String>) -> T): T =
*/ */
public fun BufferedReader.lineSequence(): Sequence<String> = LinesSequence(this).constrainOnce() public fun BufferedReader.lineSequence(): Sequence<String> = LinesSequence(this).constrainOnce()
deprecated("Use lineSequence() instead to avoid conflict with JDK8 lines() method.", ReplaceWith("lineSequence()")) @Deprecated("Use lineSequence() instead to avoid conflict with JDK8 lines() method.", ReplaceWith("lineSequence()"))
public fun BufferedReader.lines(): Sequence<String> = lineSequence() public fun BufferedReader.lines(): Sequence<String> = lineSequence()
deprecated("Use lineSequence() function which returns Sequence<String>") @Deprecated("Use lineSequence() function which returns Sequence<String>")
public fun BufferedReader.lineIterator(): Iterator<String> = lineSequence().iterator() public fun BufferedReader.lineIterator(): Iterator<String> = lineSequence().iterator()
private class LinesSequence(private val reader: BufferedReader) : Sequence<String> { private class LinesSequence(private val reader: BufferedReader) : Sequence<String> {
@@ -153,8 +153,7 @@ public class FileTreeWalk(private val start: File,
}) })
} }
tailRecursive tailrec private fun gotoNext(): File? {
private fun gotoNext(): File? {
if (end) { if (end) {
// We are already at the end // We are already at the end
return null return null
@@ -284,7 +283,7 @@ public fun File.walkBottomUp(): FileTreeWalk = walk(FileWalkDirection.BOTTOM_UP)
* *
* @param function the function to call on each file. * @param function the function to call on each file.
*/ */
deprecated("It's recommended to use walkTopDown() / walkBottomUp()") @Deprecated("It's recommended to use walkTopDown() / walkBottomUp()")
public fun File.recurse(function: (File) -> Unit): Unit { public fun File.recurse(function: (File) -> Unit): Unit {
walkTopDown().forEach { function(it) } walkTopDown().forEach { function(it) }
} }
@@ -51,7 +51,7 @@ public val File.directory: File
/** /**
* Returns parent of this abstract path name, or `null` if it has no parent. * Returns parent of this abstract path name, or `null` if it has no parent.
*/ */
@deprecated("Use parentFile", ReplaceWith("parentFile")) @Deprecated("Use parentFile", ReplaceWith("parentFile"))
public val File.parent: File? public val File.parent: File?
get() = parentFile get() = parentFile
@@ -59,7 +59,7 @@ public val File.parent: File?
* Returns the canonical path of this file. * Returns the canonical path of this file.
*/ */
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("canonicalPath")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("canonicalPath"))
public val File.canonicalPath: String public val File.canonicalPath: String
get() = getCanonicalPath() get() = getCanonicalPath()
@@ -67,7 +67,7 @@ public val File.canonicalPath: String
* Returns the file name. * Returns the file name.
*/ */
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("name")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("name"))
public val File.name: String public val File.name: String
get() = getName() get() = getName()
@@ -75,7 +75,7 @@ public val File.name: String
* Returns the file path. * Returns the file path.
*/ */
@HiddenDeclaration @HiddenDeclaration
@deprecated("Is replaced with automatic synthetic extension", ReplaceWith("path")) @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("path"))
public val File.path: String public val File.path: String
get() = getPath() get() = getPath()
@@ -178,7 +178,7 @@ public fun File.relativeTo(base: File): String {
* If this file matches the [descendant] directory or does not belong to it, * If this file matches the [descendant] directory or does not belong to it,
* then an empty string will be returned. * then an empty string will be returned.
*/ */
deprecated("Use relativeTo() function instead") @Deprecated("Use relativeTo() function instead")
public fun File.relativePath(descendant: File): String { public fun File.relativePath(descendant: File): String {
val prefix = directory.canonicalPath val prefix = directory.canonicalPath
val answer = descendant.canonicalPath val answer = descendant.canonicalPath
@@ -55,7 +55,7 @@ public annotation class JvmName(public val name: String)
/** /**
* Instructs the Kotlin compiler to generate a multifile class with this file as one o * Instructs the Kotlin compiler to generate a multifile class with this file as one o
*/ */
target(AnnotationTarget.FILE) @Target(AnnotationTarget.FILE)
@Retention(AnnotationRetention.RUNTIME) @Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented @MustBeDocumented
public annotation class JvmMultifileClass public annotation class JvmMultifileClass
@@ -21,11 +21,11 @@ import kotlin.annotation.AnnotationTarget.*
@Target(FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER) @Target(FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER)
@Retention(AnnotationRetention.RUNTIME) @Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented @MustBeDocumented
@deprecated("Use kotlin.jvm.JvmName instead", ReplaceWith("kotlin.jvm.JvmName")) @Deprecated("Use kotlin.jvm.platformName instead", ReplaceWith("kotlin.jvm.platformName"))
public annotation class platformName(public val name: String) public annotation class platformName(public val name: String)
@Target(FUNCTION, PROPERTY, PROPERTY_GETTER, PROPERTY_SETTER) @Target(FUNCTION, PROPERTY, PROPERTY_GETTER, PROPERTY_SETTER)
@Retention(AnnotationRetention.RUNTIME) @Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented @MustBeDocumented
@deprecated("Use kotlin.jvm.JvmStatic instead", ReplaceWith("kotlin.jvm.JvmStatic")) @Deprecated("Use kotlin.jvm.JvmStatic instead", ReplaceWith("kotlin.jvm.JvmStatic"))
public annotation class platformStatic public annotation class platformStatic
@@ -19,7 +19,7 @@ public object Delegates {
* specified block of code. Supports lazy initialization semantics for properties. * specified block of code. Supports lazy initialization semantics for properties.
* @param initializer the function that returns the value of the property. * @param initializer the function that returns the value of the property.
*/ */
deprecated("Use lazy {} instead in kotlin package", ReplaceWith("kotlin.lazy(LazyThreadSafetyMode.NONE, initializer)")) @Deprecated("Use lazy {} instead in kotlin package", ReplaceWith("kotlin.lazy(LazyThreadSafetyMode.NONE, initializer)"))
public fun lazy<T>(initializer: () -> T): ReadOnlyProperty<Any?, T> = LazyVal(initializer) public fun lazy<T>(initializer: () -> T): ReadOnlyProperty<Any?, T> = LazyVal(initializer)
/** /**
@@ -30,7 +30,7 @@ public object Delegates {
* the property delegate object itself is used as a lock. * the property delegate object itself is used as a lock.
* @param initializer the function that returns the value of the property. * @param initializer the function that returns the value of the property.
*/ */
deprecated("Use lazy(lock) {} instead in kotlin package", ReplaceWith("lazy(lock, initializer)")) @Deprecated("Use lazy(lock) {} instead in kotlin package", ReplaceWith("lazy(lock, initializer)"))
public fun blockingLazy<T>(lock: Any?, initializer: () -> T): ReadOnlyProperty<Any?, T> = BlockingLazyVal(lock, initializer) public fun blockingLazy<T>(lock: Any?, initializer: () -> T): ReadOnlyProperty<Any?, T> = BlockingLazyVal(lock, initializer)
/** /**
@@ -40,7 +40,7 @@ public object Delegates {
* The property delegate object itself is used as a lock. * The property delegate object itself is used as a lock.
* @param initializer the function that returns the value of the property. * @param initializer the function that returns the value of the property.
*/ */
deprecated("Use lazy {} instead in kotlin package", ReplaceWith("kotlin.lazy(initializer)")) @Deprecated("Use lazy {} instead in kotlin package", ReplaceWith("kotlin.lazy(initializer)"))
public fun blockingLazy<T>(initializer: () -> T): ReadOnlyProperty<Any?, T> = BlockingLazyVal(null, initializer) public fun blockingLazy<T>(initializer: () -> T): ReadOnlyProperty<Any?, T> = BlockingLazyVal(null, initializer)
/** /**
@@ -49,7 +49,7 @@ public object Delegates {
* @param onChange the callback which is called after the change of the property is made. The value of the property * @param onChange the callback which is called after the change of the property is made. The value of the property
* has already been changed when this callback is invoked. * has already been changed when this callback is invoked.
*/ */
public inline fun observable<T>(initialValue: T, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) onChange: (property: PropertyMetadata, oldValue: T, newValue: T) -> Unit): public inline fun observable<T>(initialValue: T, crossinline onChange: (property: PropertyMetadata, oldValue: T, newValue: T) -> Unit):
ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) { ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: PropertyMetadata, oldValue: T, newValue: T) = onChange(property, oldValue, newValue) override fun afterChange(property: PropertyMetadata, oldValue: T, newValue: T) = onChange(property, oldValue, newValue)
} }
@@ -63,7 +63,7 @@ public object Delegates {
* If the callback returns `true` the value of the property is being set to the new value, * If the callback returns `true` the value of the property is being set to the new value,
* and if the callback returns `false` the new value is discarded and the property remains its old value. * and if the callback returns `false` the new value is discarded and the property remains its old value.
*/ */
public inline fun vetoable<T>(initialValue: T, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) onChange: (property: PropertyMetadata, oldValue: T, newValue: T) -> Boolean): public inline fun vetoable<T>(initialValue: T, crossinline onChange: (property: PropertyMetadata, oldValue: T, newValue: T) -> Boolean):
ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) { ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) {
override fun beforeChange(property: PropertyMetadata, oldValue: T, newValue: T): Boolean = onChange(property, oldValue, newValue) override fun beforeChange(property: PropertyMetadata, oldValue: T, newValue: T): Boolean = onChange(property, oldValue, newValue)
} }
@@ -73,7 +73,7 @@ public object Delegates {
* as a key. * as a key.
* @param map the map where the property values are stored. * @param map the map where the property values are stored.
*/ */
deprecated("Delegate property to the map itself without creating a wrapper.", ReplaceWith("map")) @Deprecated("Delegate property to the map itself without creating a wrapper.", ReplaceWith("map"))
public fun mapVar<T>(map: MutableMap<in String, Any?>): ReadWriteProperty<Any?, T> { public fun mapVar<T>(map: MutableMap<in String, Any?>): ReadWriteProperty<Any?, T> {
return FixedMapVar<Any?, String, T>(map, propertyNameSelector, throwKeyNotFound) return FixedMapVar<Any?, String, T>(map, propertyNameSelector, throwKeyNotFound)
} }
@@ -94,7 +94,7 @@ public object Delegates {
* as a key. * as a key.
* @param map the map where the property values are stored. * @param map the map where the property values are stored.
*/ */
deprecated("Delegate property to the map itself without creating a wrapper.", ReplaceWith("map")) @Deprecated("Delegate property to the map itself without creating a wrapper.", ReplaceWith("map"))
public fun mapVal<T>(map: Map<in String, Any?>): ReadOnlyProperty<Any?, T> { public fun mapVal<T>(map: Map<in String, Any?>): ReadOnlyProperty<Any?, T> {
return FixedMapVal<Any?, String, T>(map, propertyNameSelector, throwKeyNotFound) return FixedMapVal<Any?, String, T>(map, propertyNameSelector, throwKeyNotFound)
} }
@@ -125,7 +125,7 @@ private class NotNullVar<T: Any>() : ReadWriteProperty<Any?, T> {
} }
deprecated("Use Delegates.vetoable() instead or construct implementation of abstract ObservableProperty", ReplaceWith("Delegates.vetoable(initialValue, onChange)")) @Deprecated("Use Delegates.vetoable() instead or construct implementation of abstract ObservableProperty", ReplaceWith("Delegates.vetoable(initialValue, onChange)"))
public fun ObservableProperty<T>(initialValue: T, onChange: (property: PropertyMetadata, oldValue: T, newValue: T) -> Boolean): ObservableProperty<T> = public fun ObservableProperty<T>(initialValue: T, onChange: (property: PropertyMetadata, oldValue: T, newValue: T) -> Boolean): ObservableProperty<T> =
object : ObservableProperty<T>(initialValue) { object : ObservableProperty<T>(initialValue) {
override fun beforeChange(property: PropertyMetadata, oldValue: T, newValue: T): Boolean = onChange(property, oldValue, newValue) override fun beforeChange(property: PropertyMetadata, oldValue: T, newValue: T): Boolean = onChange(property, oldValue, newValue)
@@ -189,7 +189,7 @@ private class LazyVal<T>(private val initializer: () -> T) : ReadOnlyProperty<An
private class BlockingLazyVal<T>(lock: Any?, private val initializer: () -> T) : ReadOnlyProperty<Any?, T> { private class BlockingLazyVal<T>(lock: Any?, private val initializer: () -> T) : ReadOnlyProperty<Any?, T> {
private val lock = lock ?: this private val lock = lock ?: this
private volatile var value: Any? = null @volatile private var value: Any? = null
public override fun get(thisRef: Any?, property: PropertyMetadata): T { public override fun get(thisRef: Any?, property: PropertyMetadata): T {
val _v1 = value val _v1 = value
@@ -215,9 +215,9 @@ private class BlockingLazyVal<T>(lock: Any?, private val initializer: () -> T) :
* Exception thrown by the default implementation of property delegates which store values in a map * Exception thrown by the default implementation of property delegates which store values in a map
* when the map does not contain the corresponding key. * when the map does not contain the corresponding key.
*/ */
deprecated("Do not throw or catch this exception, use NoSuchElementException instead.") @Deprecated("Do not throw or catch this exception, use NoSuchElementException instead.")
public class KeyMissingException public class KeyMissingException
deprecated("Throw NoSuchElementException instead.", ReplaceWith("NoSuchElementException(message)")) @Deprecated("Throw NoSuchElementException instead.", ReplaceWith("NoSuchElementException(message)"))
constructor(message: String): NoSuchElementException(message) constructor(message: String): NoSuchElementException(message)
@@ -24,7 +24,7 @@ public fun <V> Map<in String, *>.get(thisRef: Any?, property: PropertyMetadata):
* *
* @throws NoSuchElementException when the map doesn't contain value for the property name and doesn't provide an implicit default (see [withDefault]). * @throws NoSuchElementException when the map doesn't contain value for the property name and doesn't provide an implicit default (see [withDefault]).
*/ */
platformName("getVar") @platformName("getVar")
public fun <V> MutableMap<in String, in V>.get(thisRef: Any?, property: PropertyMetadata): V = getOrImplicitDefault(property.name) as V public fun <V> MutableMap<in String, in V>.get(thisRef: Any?, property: PropertyMetadata): V = getOrImplicitDefault(property.name) as V
/** /**
@@ -3,7 +3,7 @@ package kotlin.properties
import java.util.HashMap import java.util.HashMap
import java.util.ArrayList import java.util.ArrayList
deprecated("This class is part of an old, incomplete and suboptimal design of change notifications and is going to be removed") @Deprecated("This class is part of an old, incomplete and suboptimal design of change notifications and is going to be removed")
public class ChangeEvent( public class ChangeEvent(
public val source: Any, public val source: Any,
public val name: String, public val name: String,
@@ -13,7 +13,7 @@ public class ChangeEvent(
override fun toString(): String = "ChangeEvent($name, $oldValue, $newValue)" override fun toString(): String = "ChangeEvent($name, $oldValue, $newValue)"
} }
deprecated("This class is part of an old, incomplete and suboptimal design of change notifications and is going to be removed") @Deprecated("This class is part of an old, incomplete and suboptimal design of change notifications and is going to be removed")
public interface ChangeListener { public interface ChangeListener {
public fun onPropertyChange(event: ChangeEvent): Unit public fun onPropertyChange(event: ChangeEvent): Unit
} }
@@ -23,7 +23,7 @@ public interface ChangeListener {
* updates for easier binding to user interfaces, undo/redo command stacks and * updates for easier binding to user interfaces, undo/redo command stacks and
* change tracking mechanisms for persistence or distributed change notifications. * change tracking mechanisms for persistence or distributed change notifications.
*/ */
deprecated("This class is part of an old, incomplete and suboptimal design of change notifications and is going to be removed") @Deprecated("This class is part of an old, incomplete and suboptimal design of change notifications and is going to be removed")
public abstract class ChangeSupport { public abstract class ChangeSupport {
private var allListeners: MutableList<ChangeListener>? = null private var allListeners: MutableList<ChangeListener>? = null
private var nameListeners: MutableMap<String, MutableList<ChangeListener>>? = null private var nameListeners: MutableMap<String, MutableList<ChangeListener>>? = null
+3 -3
View File
@@ -5,11 +5,11 @@ package kotlin.test
/** Asserts that the given [block] returns `false`. */ /** Asserts that the given [block] returns `false`. */
@deprecated("Use assertFalse instead.", ReplaceWith("assertFalse(message, block)")) @Deprecated("Use assertFalse instead.", ReplaceWith("assertFalse(message, block)"))
public fun assertNot(message: String, block: () -> Boolean): Unit = assertFalse(message, block) public fun assertNot(message: String, block: () -> Boolean): Unit = assertFalse(message, block)
/** Asserts that the given [block] returns `false`. */ /** Asserts that the given [block] returns `false`. */
@deprecated("Use assertFalse instead.", ReplaceWith("assertFalse(null, block)")) @Deprecated("Use assertFalse instead.", ReplaceWith("assertFalse(null, block)"))
public fun assertNot(block: () -> Boolean): Unit = assertFalse(block = block) public fun assertNot(block: () -> Boolean): Unit = assertFalse(block = block)
/** Asserts that the given [block] returns `true`. */ /** Asserts that the given [block] returns `true`. */
@@ -72,7 +72,7 @@ public fun <T> expect(expected: T, message: String?, block: () -> T) {
assertEquals(expected, block(), message) assertEquals(expected, block(), message)
} }
@deprecated("Use assertFails instead.", ReplaceWith("assertFails(block)")) @Deprecated("Use assertFails instead.", ReplaceWith("assertFails(block)"))
public fun fails(block: () -> Unit): Throwable? = assertFails(block) public fun fails(block: () -> Unit): Throwable? = assertFails(block)
/** Asserts that given function [block] fails by throwing an exception. */ /** Asserts that given function [block] fails by throwing an exception. */
+2 -2
View File
@@ -3,7 +3,7 @@ package kotlin.test
import java.util.ServiceLoader import java.util.ServiceLoader
import kotlin.reflect.KClass import kotlin.reflect.KClass
@deprecated("Use assertFailsWith instead.", ReplaceWith("assertFailsWith(exceptionClass, block)")) @Deprecated("Use assertFailsWith instead.", ReplaceWith("assertFailsWith(exceptionClass, block)"))
public fun <T: Throwable> failsWith(exceptionClass: Class<T>, block: ()-> Any): T = assertFailsWith(exceptionClass, { block() }) public fun <T: Throwable> failsWith(exceptionClass: Class<T>, block: ()-> Any): T = assertFailsWith(exceptionClass, { block() })
/** Asserts that a [block] fails with a specific exception being thrown. */ /** Asserts that a [block] fails with a specific exception being thrown. */
@@ -32,7 +32,7 @@ public fun <T: Throwable> assertFailsWith(exceptionClass: KClass<T>, message: St
/** Asserts that a [block] fails with a specific exception of type [T] being thrown. /** Asserts that a [block] fails with a specific exception of type [T] being thrown.
* Since inline method doesn't allow to trace where it was invoked, it is required to pass a [message] to distinguish this method call from others. * Since inline method doesn't allow to trace where it was invoked, it is required to pass a [message] to distinguish this method call from others.
*/ */
public inline fun <reified T: Throwable> assertFailsWith(message: String, @noinline block: () -> Unit): T = assertFailsWith(T::class.java, message, block) public inline fun <reified T: Throwable> assertFailsWith(message: String, noinline block: () -> Unit): T = assertFailsWith(T::class.java, message, block)
/** /**
+2 -2
View File
@@ -58,10 +58,10 @@ public fun Char.isJavaIdentifierPart(): Boolean = Character.isJavaIdentifierPart
*/ */
public fun Char.isJavaIdentifierStart(): Boolean = Character.isJavaIdentifierStart(this) public fun Char.isJavaIdentifierStart(): Boolean = Character.isJavaIdentifierStart(this)
deprecated("Please use Char.isJavaIdentifierStart() instead") @Deprecated("Please use Char.isJavaIdentifierStart() instead")
public fun Char.isJavaLetter(): Boolean = Character.isJavaLetter(this) public fun Char.isJavaLetter(): Boolean = Character.isJavaLetter(this)
deprecated("Please use Char.isJavaIdentifierPart() instead") @Deprecated("Please use Char.isJavaIdentifierPart() instead")
public fun Char.isJavaLetterOrDigit(): Boolean = Character.isJavaLetterOrDigit(this) public fun Char.isJavaLetterOrDigit(): Boolean = Character.isJavaLetterOrDigit(this)
/** /**
@@ -12,38 +12,38 @@ public object Charsets {
/** /**
* Eight-bit UCS Transformation Format. * Eight-bit UCS Transformation Format.
*/ */
platformStatic @platformStatic
public val UTF_8: Charset = Charset.forName("UTF-8") public val UTF_8: Charset = Charset.forName("UTF-8")
/** /**
* Sixteen-bit UCS Transformation Format, byte order identified by an * Sixteen-bit UCS Transformation Format, byte order identified by an
* optional byte-order mark. * optional byte-order mark.
*/ */
platformStatic @platformStatic
public val UTF_16: Charset = Charset.forName("UTF-16") public val UTF_16: Charset = Charset.forName("UTF-16")
/** /**
* Sixteen-bit UCS Transformation Format, big-endian byte order. * Sixteen-bit UCS Transformation Format, big-endian byte order.
*/ */
platformStatic @platformStatic
public val UTF_16BE: Charset = Charset.forName("UTF-16BE") public val UTF_16BE: Charset = Charset.forName("UTF-16BE")
/** /**
* Sixteen-bit UCS Transformation Format, little-endian byte order. * Sixteen-bit UCS Transformation Format, little-endian byte order.
*/ */
platformStatic @platformStatic
public val UTF_16LE: Charset = Charset.forName("UTF-16LE") public val UTF_16LE: Charset = Charset.forName("UTF-16LE")
/** /**
* Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the
* Unicode character set. * Unicode character set.
*/ */
platformStatic @platformStatic
public val US_ASCII: Charset = Charset.forName("US-ASCII") public val US_ASCII: Charset = Charset.forName("US-ASCII")
/** /**
* ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1. * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.
*/ */
platformStatic @platformStatic
public val ISO_8859_1: Charset = Charset.forName("ISO-8859-1") public val ISO_8859_1: Charset = Charset.forName("ISO-8859-1")
} }
+10 -10
View File
@@ -6,11 +6,11 @@ import kotlin.text.MatchResult
import kotlin.text.Regex import kotlin.text.Regex
/** 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 */
deprecated("Use removeSurrounding(text, text) or removePrefix(text).removeSuffix(text)") @Deprecated("Use removeSurrounding(text, text) or removePrefix(text).removeSuffix(text)")
public fun String.trim(text: String): String = removePrefix(text).removeSuffix(text) public fun String.trim(text: String): String = removePrefix(text).removeSuffix(text)
/** Returns the string with the prefix and postfix text trimmed */ /** Returns the string with the prefix and postfix text trimmed */
deprecated("Use removeSurrounding(prefix, suffix) or removePrefix(prefix).removeSuffix(suffix)") @Deprecated("Use removeSurrounding(prefix, suffix) or removePrefix(prefix).removeSuffix(suffix)")
public fun String.trim(prefix: String, postfix: String): String = removePrefix(prefix).removeSuffix(postfix) public fun String.trim(prefix: String, postfix: String): String = removePrefix(prefix).removeSuffix(postfix)
/** /**
@@ -79,10 +79,10 @@ public fun String.trimStart(vararg chars: Char): String = trimStart { it in char
*/ */
public fun String.trimEnd(vararg chars: Char): String = trimEnd { it in chars } public fun String.trimEnd(vararg chars: Char): String = trimEnd { it in chars }
deprecated("Use removePrefix() instead", ReplaceWith("removePrefix(prefix)")) @Deprecated("Use removePrefix() instead", ReplaceWith("removePrefix(prefix)"))
public fun String.trimLeading(prefix: String): String = removePrefix(prefix) public fun String.trimLeading(prefix: String): String = removePrefix(prefix)
deprecated("Use removeSuffix() instead", ReplaceWith("removeSuffix(postfix)")) @Deprecated("Use removeSuffix() instead", ReplaceWith("removeSuffix(postfix)"))
public fun String.trimTrailing(postfix: String): String = removeSuffix(postfix) public fun String.trimTrailing(postfix: String): String = removeSuffix(postfix)
/** /**
@@ -95,7 +95,7 @@ public fun String.trim(): String = trim { it.isWhitespace() }
*/ */
public fun String.trimStart(): String = trimStart { it.isWhitespace() } public fun String.trimStart(): String = trimStart { it.isWhitespace() }
deprecated("Use trimStart instead.", ReplaceWith("trimStart()")) @Deprecated("Use trimStart instead.", ReplaceWith("trimStart()"))
public fun String.trimLeading(): String = trimStart { it.isWhitespace() } public fun String.trimLeading(): String = trimStart { it.isWhitespace() }
/** /**
@@ -103,7 +103,7 @@ public fun String.trimLeading(): String = trimStart { it.isWhitespace() }
*/ */
public fun String.trimEnd(): String = trimEnd { it.isWhitespace() } public fun String.trimEnd(): String = trimEnd { it.isWhitespace() }
deprecated("Use trimEnd instead.", ReplaceWith("trimEnd()")) @Deprecated("Use trimEnd instead.", ReplaceWith("trimEnd()"))
public fun String.trimTrailing(): String = trimEnd { it.isWhitespace() } public fun String.trimTrailing(): String = trimEnd { it.isWhitespace() }
/** /**
@@ -149,8 +149,8 @@ public fun String.padEnd(length: Int, padChar: Char = ' '): String {
} }
/** Returns `true` if the string is not `null` and not empty */ /** Returns `true` if the string is not `null` and not empty */
deprecated("Use !isNullOrEmpty() or isNullOrEmpty().not() for nullable strings.", ReplaceWith("this != null && this.isNotEmpty()")) @Deprecated("Use !isNullOrEmpty() or isNullOrEmpty().not() for nullable strings.", ReplaceWith("this != null && this.isNotEmpty()"))
platformName("isNotEmptyNullable") @platformName("isNotEmptyNullable")
public fun String?.isNotEmpty(): Boolean = this != null && this.length() > 0 public fun String?.isNotEmpty(): Boolean = this != null && this.length() > 0
/** /**
@@ -738,7 +738,7 @@ public fun String.indexOf(char: Char, startIndex: Int = 0, ignoreCase: Boolean =
* @param ignoreCase `true` to ignore character case when matching a string. By default `false`. * @param ignoreCase `true` to ignore character case when matching a string. By default `false`.
* @returns An index of the first occurrence of [string] or -1 if none is found. * @returns An index of the first occurrence of [string] or -1 if none is found.
*/ */
kotlin.jvm.jvmOverloads @kotlin.jvm.jvmOverloads
public fun String.indexOf(string: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int { public fun String.indexOf(string: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int {
return if (ignoreCase) return if (ignoreCase)
indexOfAny(listOf(string), startIndex, ignoreCase) indexOfAny(listOf(string), startIndex, ignoreCase)
@@ -920,7 +920,7 @@ public fun String.splitToSequence(vararg delimiters: String, ignoreCase: Boolean
public fun String.split(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String> = public fun String.split(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String> =
splitToSequence(*delimiters, ignoreCase = ignoreCase, limit = limit).toList() splitToSequence(*delimiters, ignoreCase = ignoreCase, limit = limit).toList()
deprecated("Use split(delimiters) instead.", ReplaceWith("split(*delimiters, ignoreCase = ignoreCase, limit = limit)")) @Deprecated("Use split(delimiters) instead.", ReplaceWith("split(*delimiters, ignoreCase = ignoreCase, limit = limit)"))
public fun String.splitBy(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String> = public fun String.splitBy(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String> =
splitToSequence(*delimiters, ignoreCase = ignoreCase, limit = limit).toList() splitToSequence(*delimiters, ignoreCase = ignoreCase, limit = limit).toList()
+10 -10
View File
@@ -32,7 +32,7 @@ private fun String.nativeLastIndexOf(str: String, fromIndex: Int): Int = (this a
/** /**
* Compares this string to another string, ignoring case considerations. * Compares this string to another string, ignoring case considerations.
*/ */
deprecated("Use equals(anotherString, ignoreCase = true) instead", ReplaceWith("equals(anotherString, ignoreCase = true)")) @Deprecated("Use equals(anotherString, ignoreCase = true) instead", ReplaceWith("equals(anotherString, ignoreCase = true)"))
public fun String.equalsIgnoreCase(anotherString: String): Boolean = equals(anotherString, ignoreCase = true) public fun String.equalsIgnoreCase(anotherString: String): Boolean = equals(anotherString, ignoreCase = true)
/** /**
@@ -82,14 +82,14 @@ public fun String.replaceFirst(oldValue: String, newValue: String, ignoreCase: B
return if (index < 0) this else this.replaceRange(index, index + oldValue.length(), newValue) return if (index < 0) this else this.replaceRange(index, index + oldValue.length(), newValue)
} }
deprecated("Use String.replaceFirst instead.", ReplaceWith("replaceFirst(oldValue, newValue, ignoreCase = ignoreCase)")) @Deprecated("Use String.replaceFirst instead.", ReplaceWith("replaceFirst(oldValue, newValue, ignoreCase = ignoreCase)"))
public fun String.replaceFirstLiteral(oldValue: String, newValue: String, ignoreCase: Boolean = false): String = replaceFirst(oldValue, newValue, ignoreCase = ignoreCase) public fun String.replaceFirstLiteral(oldValue: String, newValue: String, ignoreCase: Boolean = false): String = replaceFirst(oldValue, newValue, ignoreCase = ignoreCase)
/** /**
* Returns a new string obtained by replacing each substring of this string that matches the given regular expression * Returns a new string obtained by replacing each substring of this string that matches the given regular expression
* with the given [replacement]. * with the given [replacement].
*/ */
deprecated("Use String.replace(Regex, String) instead. You can convert regex parameter with .toRegex() extension function.", ReplaceWith("replace(regex.toRegex(), replacement)")) @Deprecated("Use String.replace(Regex, String) instead. You can convert regex parameter with .toRegex() extension function.", ReplaceWith("replace(regex.toRegex(), replacement)"))
public fun String.replaceAll(regex: String, replacement: String): String = (this as java.lang.String).replaceAll(regex, replacement) public fun String.replaceAll(regex: String, replacement: String): String = (this as java.lang.String).replaceAll(regex, replacement)
/** /**
@@ -272,7 +272,7 @@ public fun String.codePointCount(beginIndex: Int, endIndex: Int): Int = (this as
/** /**
* Compares two strings lexicographically, ignoring case differences. * Compares two strings lexicographically, ignoring case differences.
*/ */
deprecated("Use compareTo with true passed to ignoreCase parameter.", ReplaceWith("compareTo(str, ignoreCase = true)")) @Deprecated("Use compareTo with true passed to ignoreCase parameter.", ReplaceWith("compareTo(str, ignoreCase = true)"))
public fun String.compareToIgnoreCase(str: String): Int = (this as java.lang.String).compareToIgnoreCase(str) public fun String.compareToIgnoreCase(str: String): Int = (this as java.lang.String).compareToIgnoreCase(str)
/** /**
@@ -323,7 +323,7 @@ public fun String.isBlank(): Boolean = length() == 0 || all { it.isWhitespace()
/** /**
* Returns `true` if this string matches the given regular expression. * Returns `true` if this string matches the given regular expression.
*/ */
deprecated("Use String.matches(Regex) instead. You can convert regex parameter with .toRegex() extension function.", ReplaceWith("matches(regex.toRegex())")) @Deprecated("Use String.matches(Regex) instead. You can convert regex parameter with .toRegex() extension function.", ReplaceWith("matches(regex.toRegex())"))
public fun String.matches(regex: String): Boolean = (this as java.lang.String).matches(regex) public fun String.matches(regex: String): Boolean = (this as java.lang.String).matches(regex)
/** /**
@@ -339,7 +339,7 @@ public fun String.offsetByCodePoints(index: Int, codePointOffset: Int): Int = (t
* @param ooffset the start offset in the other string of the substring to compare. * @param ooffset the start offset in the other string of the substring to compare.
* @param len the length of the substring to compare. * @param len the length of the substring to compare.
*/ */
deprecated("Use regionMatches overload with ignoreCase as optional last parameter.", ReplaceWith("regionMatches(toffset, other, ooffset, len, ignoreCase)")) @Deprecated("Use regionMatches overload with ignoreCase as optional last parameter.", ReplaceWith("regionMatches(toffset, other, ooffset, len, ignoreCase)"))
public 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) public 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)
/** /**
@@ -423,13 +423,13 @@ public fun String.toByteArray(charset: String): ByteArray = (this as java.lang.S
*/ */
public fun String.toByteArray(charset: Charset = Charsets.UTF_8): ByteArray = (this as java.lang.String).getBytes(charset) public fun String.toByteArray(charset: Charset = Charsets.UTF_8): ByteArray = (this as java.lang.String).getBytes(charset)
deprecated("Use toByteArray() instead to emphasize copy behaviour", ReplaceWith("toByteArray()")) @Deprecated("Use toByteArray() instead to emphasize copy behaviour", ReplaceWith("toByteArray()"))
public fun String.getBytes(): ByteArray = (this as java.lang.String).getBytes() public fun String.getBytes(): ByteArray = (this as java.lang.String).getBytes()
deprecated("Use toByteArray(charset) instead to emphasize copy behaviour", ReplaceWith("toByteArray(charset)")) @Deprecated("Use toByteArray(charset) instead to emphasize copy behaviour", ReplaceWith("toByteArray(charset)"))
public fun String.getBytes(charset: Charset): ByteArray = (this as java.lang.String).getBytes(charset) public fun String.getBytes(charset: Charset): ByteArray = (this as java.lang.String).getBytes(charset)
deprecated("Use toByteArray(charset) instead to emphasize copy behaviour", ReplaceWith("toByteArray(charset)")) @Deprecated("Use toByteArray(charset) instead to emphasize copy behaviour", ReplaceWith("toByteArray(charset)"))
public fun String.getBytes(charset: String): ByteArray = (this as java.lang.String).getBytes(charset) public fun String.getBytes(charset: String): ByteArray = (this as java.lang.String).getBytes(charset)
/** /**
@@ -519,7 +519,7 @@ public inline fun <T : Appendable> String.takeWhileTo(result: T, predicate: (Cha
* Replaces every [regexp] occurence in the text with the value returned by the given function [body] that * Replaces every [regexp] occurence in the text with the value returned by the given function [body] that
* takes a [MatchResult]. * takes a [MatchResult].
*/ */
deprecated("Use String.replace(Regex, (MatchResult)->String) instead. You can convert regex parameter with .toRegex() extension function.") @Deprecated("Use String.replace(Regex, (MatchResult)->String) instead. You can convert regex parameter with .toRegex() extension function.")
public fun String.replaceAll(regexp: String, body: (java.util.regex.MatchResult) -> String): String { public fun String.replaceAll(regexp: String, body: (java.util.regex.MatchResult) -> String): String {
val sb = StringBuilder(this.length()) val sb = StringBuilder(this.length())
val p = regexp.toPattern() val p = regexp.toPattern()
@@ -108,7 +108,7 @@ public class Regex internal constructor(private val nativePattern: Pattern) {
/** The set of options that were used to create this regular expression. */ /** The set of options that were used to create this regular expression. */
public val options: Set<RegexOption> = fromInt(nativePattern.flags(), RegexOption.values()) public val options: Set<RegexOption> = fromInt(nativePattern.flags(), RegexOption.values())
deprecated("To get the Matcher from java.util.regex.Pattern use toPattern to convert string to Pattern, or migrate to Regex API") @Deprecated("To get the Matcher from java.util.regex.Pattern use toPattern to convert string to Pattern, or migrate to Regex API")
public fun matcher(input: CharSequence): Matcher = nativePattern.matcher(input) public fun matcher(input: CharSequence): Matcher = nativePattern.matcher(input)
/** Indicates whether the regular expression matches the entire [input]. */ /** Indicates whether the regular expression matches the entire [input]. */
@@ -3,7 +3,7 @@ package kotlin
private object _Assertions private object _Assertions
deprecated("Must be public to make assert() inlinable") @Deprecated("Must be public to make assert() inlinable")
public val ASSERTIONS_ENABLED: Boolean = _Assertions.javaClass.desiredAssertionStatus() public val ASSERTIONS_ENABLED: Boolean = _Assertions.javaClass.desiredAssertionStatus()
/** /**
@@ -18,7 +18,7 @@ public fun assert(value: Boolean) {
* Throws an [AssertionError] with an optional [message] if the [value] is false * Throws an [AssertionError] with an optional [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.
*/ */
@deprecated("Use assert with lazy message instead.", ReplaceWith("assert(value) { message }")) @Deprecated("Use assert with lazy message instead.", ReplaceWith("assert(value) { message }"))
public fun assert(value: Boolean, message: Any = "Assertion failed") { public fun assert(value: Boolean, message: Any = "Assertion failed") {
if (ASSERTIONS_ENABLED) { if (ASSERTIONS_ENABLED) {
if (!value) { if (!value) {
+1 -1
View File
@@ -3,7 +3,7 @@ package kotlin
/** /**
* Executes the given function [body] the number of times equal to the value of this integer. * Executes the given function [body] the number of times equal to the value of this integer.
*/ */
deprecated("Use repeat(n) { body } instead.") @Deprecated("Use repeat(n) { body } instead.")
public 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) {
+1 -1
View File
@@ -37,7 +37,7 @@ public val <T: Any> T.javaClass : Class<T>
* Returns the Java class for the specified type. * Returns the Java class for the specified type.
*/ */
@Intrinsic("kotlin.javaClass.function") @Intrinsic("kotlin.javaClass.function")
@deprecated("Use the class reference and .java extension property instead: MyClass::class.java", ReplaceWith("T::class.java")) @Deprecated("Use the class reference and .java extension property instead: MyClass::class.java", ReplaceWith("T::class.java"))
public fun <reified T: Any> javaClass(): Class<T> = T::class.java public fun <reified T: Any> javaClass(): Class<T> = T::class.java
/** /**
+1 -1
View File
@@ -53,7 +53,7 @@ private object UNINITIALIZED_VALUE
private open class LazyImpl<out T>(initializer: () -> T) : Lazy<T>(), Serializable { private open class LazyImpl<out T>(initializer: () -> T) : Lazy<T>(), Serializable {
private var initializer: (() -> T)? = initializer private var initializer: (() -> T)? = initializer
private volatile var _value: Any? = UNINITIALIZED_VALUE @volatile private var _value: Any? = UNINITIALIZED_VALUE
protected open val lock: Any protected open val lock: Any
get() = this get() = this
+14 -14
View File
@@ -25,7 +25,7 @@ import kotlin.platform.platformName
* objects. As soon as the [Comparable] instances returned by a function for [a] and [b] values do not * objects. As soon as the [Comparable] instances returned by a function for [a] and [b] values do not
* compare as equal, the result of that comparison is returned. * compare as equal, the result of that comparison is returned.
*/ */
deprecated("Use selector functions accepting nullable T as a receiver.") @Deprecated("Use selector functions accepting nullable T as a receiver.")
public fun <T : Any> compareValuesBy(a: T?, b: T?, vararg functions: (T) -> Comparable<*>?): Int { public fun <T : Any> compareValuesBy(a: T?, b: T?, vararg functions: (T) -> Comparable<*>?): Int {
require(functions.size() > 0) require(functions.size() > 0)
if (a === b) return 0 if (a === b) return 0
@@ -47,7 +47,7 @@ public fun <T : Any> compareValuesBy(a: T?, b: T?, vararg functions: (T) -> Comp
* compare as equal, the result of that comparison is returned. * compare as equal, the result of that comparison is returned.
*/ */
// TODO: Remove platformName after M13 // TODO: Remove platformName after M13
platformName("compareValuesByNullable") @platformName("compareValuesByNullable")
public fun <T> compareValuesBy(a: T, b: T, vararg selectors: (T) -> Comparable<*>?): Int { public fun <T> compareValuesBy(a: T, b: T, vararg selectors: (T) -> Comparable<*>?): Int {
require(selectors.size() > 0) require(selectors.size() > 0)
for (fn in selectors) { for (fn in selectors) {
@@ -82,7 +82,7 @@ public inline fun <T, K> compareValuesBy(a: T, b: T, comparator: Comparator<in K
///** ///**
// * Compares two values using the specified [comparator]. // * Compares two values using the specified [comparator].
// */ // */
//@suppress("NOTHING_TO_INLINE") //@Suppress("NOTHING_TO_INLINE")
//public inline fun <T> compareValuesWith(a: T, b: T, comparator: Comparator<T>): Int = comparator.compare(a, b) //public inline fun <T> compareValuesWith(a: T, b: T, comparator: Comparator<T>): Int = comparator.compare(a, b)
// //
@@ -113,13 +113,13 @@ public fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T>
/** /**
* Creates a comparator using the sequence of functions to calculate a result of comparison. * Creates a comparator using the sequence of functions to calculate a result of comparison.
*/ */
deprecated("Use compareBy() instead", ReplaceWith("compareBy(*functions)")) @Deprecated("Use compareBy() instead", ReplaceWith("compareBy(*functions)"))
public fun <T> comparator(vararg functions: (T) -> Comparable<*>?): Comparator<T> = compareBy(*functions) public fun <T> comparator(vararg functions: (T) -> Comparable<*>?): Comparator<T> = compareBy(*functions)
/** /**
* Creates a comparator using the function to transform value to a [Comparable] instance for comparison. * Creates a comparator using the function to transform value to a [Comparable] instance for comparison.
*/ */
inline public fun <T> compareBy(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> Comparable<*>?): Comparator<T> { inline public fun <T> compareBy(crossinline selector: (T) -> Comparable<*>?): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int = compareValuesBy(a, b, selector) public override fun compare(a: T, b: T): Int = compareValuesBy(a, b, selector)
} }
@@ -129,7 +129,7 @@ inline public fun <T> compareBy(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) se
* Creates a comparator using the [selector] function to transform values being compared and then applying * Creates a comparator using the [selector] function to transform values being compared and then applying
* the specified [comparator] to compare transformed values. * the specified [comparator] to compare transformed values.
*/ */
inline public fun <T, K> compareBy(comparator: Comparator<in K>, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> K): Comparator<T> { inline public fun <T, K> compareBy(comparator: Comparator<in K>, crossinline selector: (T) -> K): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int = compareValuesBy(a, b, comparator, selector) public override fun compare(a: T, b: T): Int = compareValuesBy(a, b, comparator, selector)
} }
@@ -138,7 +138,7 @@ inline public fun <T, K> compareBy(comparator: Comparator<in K>, inlineOptions(I
/** /**
* Creates a descending comparator using the function to transform value to a [Comparable] instance for comparison. * Creates a descending comparator using the function to transform value to a [Comparable] instance for comparison.
*/ */
inline public fun <T> compareByDescending(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> Comparable<*>?): Comparator<T> { inline public fun <T> compareByDescending(crossinline selector: (T) -> Comparable<*>?): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int = compareValuesBy(b, a, selector) public override fun compare(a: T, b: T): Int = compareValuesBy(b, a, selector)
} }
@@ -150,7 +150,7 @@ inline public fun <T> compareByDescending(inlineOptions(InlineOption.ONLY_LOCAL_
* *
* Note that an order of [comparator] is reversed by this wrapper. * Note that an order of [comparator] is reversed by this wrapper.
*/ */
inline public fun <T, K> compareByDescending(comparator: Comparator<in K>, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> K): Comparator<T> { inline public fun <T, K> compareByDescending(comparator: Comparator<in K>, crossinline selector: (T) -> K): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int = compareValuesBy(b, a, comparator, selector) public override fun compare(a: T, b: T): Int = compareValuesBy(b, a, comparator, selector)
} }
@@ -160,7 +160,7 @@ inline public fun <T, K> compareByDescending(comparator: Comparator<in K>, inlin
* Creates a comparator comparing values after the primary comparator defined them equal. It uses * Creates a comparator comparing values after the primary comparator defined them equal. It uses
* the function to transform value to a [Comparable] instance for comparison. * the function to transform value to a [Comparable] instance for comparison.
*/ */
inline public fun <T> Comparator<T>.thenBy(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> Comparable<*>?): Comparator<T> { inline public fun <T> Comparator<T>.thenBy(crossinline selector: (T) -> Comparable<*>?): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int { public override fun compare(a: T, b: T): Int {
val previousCompare = this@thenBy.compare(a, b) val previousCompare = this@thenBy.compare(a, b)
@@ -173,7 +173,7 @@ inline public fun <T> Comparator<T>.thenBy(inlineOptions(InlineOption.ONLY_LOCAL
* Creates a comparator comparing values after the primary comparator defined them equal. It uses * Creates a comparator comparing values after the primary comparator defined them equal. It uses
* the [selector] function to transform values and then compares them with the given [comparator]. * the [selector] function to transform values and then compares them with the given [comparator].
*/ */
inline public fun <T, K> Comparator<T>.thenBy(comparator: Comparator<in K>, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> K): Comparator<T> { inline public fun <T, K> Comparator<T>.thenBy(comparator: Comparator<in K>, crossinline selector: (T) -> K): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int { public override fun compare(a: T, b: T): Int {
val previousCompare = this@thenBy.compare(a, b) val previousCompare = this@thenBy.compare(a, b)
@@ -186,7 +186,7 @@ inline public fun <T, K> Comparator<T>.thenBy(comparator: Comparator<in K>, inli
* Creates a descending comparator using the primary comparator and * Creates a descending comparator using the primary comparator and
* the function to transform value to a [Comparable] instance for comparison. * the function to transform value to a [Comparable] instance for comparison.
*/ */
inline public fun <T> Comparator<T>.thenByDescending(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> Comparable<*>?): Comparator<T> { inline public fun <T> Comparator<T>.thenByDescending(crossinline selector: (T) -> Comparable<*>?): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int { public override fun compare(a: T, b: T): Int {
val previousCompare = this@thenByDescending.compare(a, b) val previousCompare = this@thenByDescending.compare(a, b)
@@ -199,7 +199,7 @@ inline public fun <T> Comparator<T>.thenByDescending(inlineOptions(InlineOption.
* Creates a descending comparator comparing values after the primary comparator defined them equal. It uses * Creates a descending comparator comparing values after the primary comparator defined them equal. It uses
* the [selector] function to transform values and then compares them with the given [comparator]. * the [selector] function to transform values and then compares them with the given [comparator].
*/ */
inline public fun <T, K> Comparator<T>.thenByDescending(comparator: Comparator<in K>, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) selector: (T) -> K): Comparator<T> { inline public fun <T, K> Comparator<T>.thenByDescending(comparator: Comparator<in K>, crossinline selector: (T) -> K): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int { public override fun compare(a: T, b: T): Int {
val previousCompare = this@thenByDescending.compare(a, b) val previousCompare = this@thenByDescending.compare(a, b)
@@ -212,7 +212,7 @@ inline public fun <T, K> Comparator<T>.thenByDescending(comparator: Comparator<i
/** /**
* Creates a comparator using the function to calculate a result of comparison. * Creates a comparator using the function to calculate a result of comparison.
*/ */
inline public fun <T> comparator(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) comparison: (T, T) -> Int): Comparator<T> { inline public fun <T> comparator(crossinline comparison: (T, T) -> Int): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int = comparison(a, b) public override fun compare(a: T, b: T): Int = comparison(a, b)
} }
@@ -221,7 +221,7 @@ inline public fun <T> comparator(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) c
/** /**
* Creates a comparator using the primary comparator and function to calculate a result of comparison. * Creates a comparator using the primary comparator and function to calculate a result of comparison.
*/ */
inline public fun <T> Comparator<T>.thenComparator(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) comparison: (T, T) -> Int): Comparator<T> { inline public fun <T> Comparator<T>.thenComparator(crossinline comparison: (T, T) -> Int): Comparator<T> {
return object : Comparator<T> { return object : Comparator<T> {
public override fun compare(a: T, b: T): Int { public override fun compare(a: T, b: T): Int {
val previousCompare = this@thenComparator.compare(a, b) val previousCompare = this@thenComparator.compare(a, b)
@@ -14,7 +14,7 @@ public fun require(value: Boolean): Unit = require(value) { "Failed requirement"
* *
* @sample test.collections.PreconditionsTest.failingRequireWithMessage * @sample test.collections.PreconditionsTest.failingRequireWithMessage
*/ */
@deprecated("Use require with lazy message instead.", ReplaceWith("require(value) { message }")) @Deprecated("Use require with lazy message instead.", ReplaceWith("require(value) { message }"))
public fun require(value: Boolean, message: Any = "Failed requirement"): Unit { public fun require(value: Boolean, message: Any = "Failed requirement"): Unit {
if (!value) { if (!value) {
throw IllegalArgumentException(message.toString()) throw IllegalArgumentException(message.toString())
@@ -44,7 +44,7 @@ public fun <T:Any> requireNotNull(value: T?): T = requireNotNull(value) { "Requi
* *
* @sample test.collections.PreconditionsTest.requireNotNull * @sample test.collections.PreconditionsTest.requireNotNull
*/ */
@deprecated("Use requireNotNull with lazy message instead.", ReplaceWith("requireNotNull(value) { message }")) @Deprecated("Use requireNotNull with lazy message instead.", ReplaceWith("requireNotNull(value) { message }"))
public fun <T:Any> requireNotNull(value: T?, message: Any = "Required value was null"): T { public fun <T:Any> requireNotNull(value: T?, message: Any = "Required value was null"): T {
if (value == null) { if (value == null) {
throw IllegalArgumentException(message.toString()) throw IllegalArgumentException(message.toString())
@@ -78,7 +78,7 @@ public fun check(value: Boolean): Unit = check(value) { "Check failed" }
* *
* @sample test.collections.PreconditionsTest.failingCheckWithMessage * @sample test.collections.PreconditionsTest.failingCheckWithMessage
*/ */
@deprecated("Use check with lazy message instead.", ReplaceWith("check(value) { message }")) @Deprecated("Use check with lazy message instead.", ReplaceWith("check(value) { message }"))
public fun check(value: Boolean, message: Any = "Check failed"): Unit { public fun check(value: Boolean, message: Any = "Check failed"): Unit {
if (!value) { if (!value) {
throw IllegalStateException(message.toString()) throw IllegalStateException(message.toString())
@@ -109,7 +109,7 @@ public fun <T:Any> checkNotNull(value: T?): T = checkNotNull(value) { "Required
* *
* @sample test.collections.PreconditionsTest.checkNotNull * @sample test.collections.PreconditionsTest.checkNotNull
*/ */
@deprecated("Use checkNotNull with lazy message instead.", ReplaceWith("checkNotNull(value) { message }")) @Deprecated("Use checkNotNull with lazy message instead.", ReplaceWith("checkNotNull(value) { message }"))
public fun <T:Any> checkNotNull(value: T?, message: Any = "Required value was null"): T { public fun <T:Any> checkNotNull(value: T?, message: Any = "Required value was null"): T {
if (value == null) { if (value == null) {
throw IllegalStateException(message.toString()) throw IllegalStateException(message.toString())
+1 -1
View File
@@ -13,7 +13,7 @@ class AnnotatedClass
class AnnotationTest { class AnnotationTest {
test fun annotationType() { @test fun annotationType() {
val annotations = javaClass<AnnotatedClass>().getAnnotations()!! val annotations = javaClass<AnnotatedClass>().getAnnotations()!!
var foundMyAnno = false var foundMyAnno = false
+2 -1
View File
@@ -7,7 +7,8 @@ import java.io.Serializable
/** /**
*/ */
class DataClassTest { class DataClassTest {
Test fun dataClass() { @Test
fun dataClass() {
val p = Person("James", 43) val p = Person("James", 43)
println("Got $p") println("Got $p")
assertEquals("Person(name=James, age=43)", "$p", "toString") assertEquals("Person(name=James, age=43)", "$p", "toString")
@@ -23,14 +23,14 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class CompanionObjectsExtensionsTest { class CompanionObjectsExtensionsTest {
test fun intTest() { @test fun intTest() {
val i = Int val i = Int
assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE) assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE)
assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE) assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE)
} }
test fun doubleTest() { @test fun doubleTest() {
val d = Double val d = Double
assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
@@ -41,7 +41,7 @@ class CompanionObjectsExtensionsTest {
assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE) assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE)
} }
test fun floatTest() { @test fun floatTest() {
val f = Float val f = Float
assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
@@ -52,34 +52,34 @@ class CompanionObjectsExtensionsTest {
assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE) assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE)
} }
test fun longTest() { @test fun longTest() {
val l = Long val l = Long
assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE) assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE)
assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE) assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE)
} }
test fun shortTest() { @test fun shortTest() {
val s = Short val s = Short
assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE) assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE)
assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE) assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE)
} }
test fun byteTest() { @test fun byteTest() {
val b = Byte val b = Byte
assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE) assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE)
assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE) assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE)
} }
test fun charTest() { @test fun charTest() {
val ch = Char val ch = Char
assertEquals(ch, Char) assertEquals(ch, Char)
} }
test fun stringTest() { @test fun stringTest() {
val s = String val s = String
assertEquals(s, String) assertEquals(s, String)
+2 -2
View File
@@ -9,12 +9,12 @@ import java.io.*
class ExceptionTest { class ExceptionTest {
test fun printStackTraceOnRuntimeException() { @test fun printStackTraceOnRuntimeException() {
assertPrintStackTrace(RuntimeException("Crikey!")) assertPrintStackTrace(RuntimeException("Crikey!"))
assertPrintStackTraceStream(RuntimeException("Crikey2")) assertPrintStackTraceStream(RuntimeException("Crikey2"))
} }
test fun printStackTraceOnError() { @test fun printStackTraceOnError() {
assertPrintStackTrace(Error("Oh dear")) assertPrintStackTrace(Error("Oh dear"))
assertPrintStackTraceStream(Error("Oh dear2")) assertPrintStackTraceStream(Error("Oh dear2"))
} }
+3 -3
View File
@@ -9,7 +9,7 @@ class GetOrElseTest {
val v2: String? = null val v2: String? = null
var counter = 0 var counter = 0
test fun defaultValue() { @test fun defaultValue() {
assertEquals("hello", v1?: "bar") assertEquals("hello", v1?: "bar")
expect("hello") { expect("hello") {
@@ -17,7 +17,7 @@ class GetOrElseTest {
} }
} }
test fun defaultValueOnNull() { @test fun defaultValueOnNull() {
assertEquals("bar", v2?: "bar") assertEquals("bar", v2?: "bar")
expect("bar") { expect("bar") {
@@ -30,7 +30,7 @@ class GetOrElseTest {
return "bar" return "bar"
} }
test fun lazyDefaultValue() { @test fun lazyDefaultValue() {
counter = 0 counter = 0
assertEquals("hello", v1?: calculateBar()) assertEquals("hello", v1?: calculateBar())
+2 -2
View File
@@ -8,7 +8,7 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class MathTest { class MathTest {
test fun testBigInteger() { @test fun testBigInteger() {
val a = BigInteger("2") val a = BigInteger("2")
val b = BigInteger("3") val b = BigInteger("3")
@@ -21,7 +21,7 @@ class MathTest {
assertEquals(BigInteger("-2"), -a remainder b) assertEquals(BigInteger("-2"), -a remainder b)
} }
test fun testBigDecimal() { @test fun testBigDecimal() {
val a = BigDecimal("2") val a = BigDecimal("2")
val b = BigDecimal("3") val b = BigDecimal("3")
+2 -2
View File
@@ -5,12 +5,12 @@ import kotlin.test.*
class NaturalLanguageTest { class NaturalLanguageTest {
test fun `strings equal`() { @test fun `strings equal`() {
val actual = "abc" val actual = "abc"
assertEquals("abc", actual) assertEquals("abc", actual)
} }
test fun `numbers equal`() { @test fun `numbers equal`() {
val actual = 5 val actual = 5
assertEquals(5, actual) assertEquals(5, actual)
} }
+3 -3
View File
@@ -8,19 +8,19 @@ import java.io.*
import org.junit.Test as test import org.junit.Test as test
class OldStdlibTest() { class OldStdlibTest() {
test fun testCollectionEmpty() { @test fun testCollectionEmpty() {
assertNot { assertNot {
listOf(0, 1, 2).isEmpty() listOf(0, 1, 2).isEmpty()
} }
} }
test fun testCollectionSize() { @test fun testCollectionSize() {
assertTrue { assertTrue {
listOf(0, 1, 2).size() == 3 listOf(0, 1, 2).size() == 3
} }
} }
test fun testInputStreamIterator() { @test fun testInputStreamIterator() {
val x = ByteArray (10) val x = ByteArray (10)
for(index in 0..9) { for(index in 0..9) {
+22 -11
View File
@@ -14,27 +14,32 @@ class OrderingTest {
val v1 = Item("wine", 9) val v1 = Item("wine", 9)
val v2 = Item("beer", 10) val v2 = Item("beer", 10)
Test fun compareByCompareTo() { @Test
fun compareByCompareTo() {
val diff = v1.compareTo(v2) val diff = v1.compareTo(v2)
assertTrue(diff < 0) assertTrue(diff < 0)
} }
Test fun compareByNameFirst() { @Test
fun compareByNameFirst() {
val diff = compareValuesBy(v1, v2, { it.name }, { it.rating }) val diff = compareValuesBy(v1, v2, { it.name }, { it.rating })
assertTrue(diff > 0) assertTrue(diff > 0)
} }
Test fun compareByRatingFirst() { @Test
fun compareByRatingFirst() {
val diff = compareValuesBy(v1, v2, { it.rating }, { it.name }) val diff = compareValuesBy(v1, v2, { it.rating }, { it.name })
assertTrue(diff < 0) assertTrue(diff < 0)
} }
Test fun compareSameObjectsByRatingFirst() { @Test
fun compareSameObjectsByRatingFirst() {
val diff = compareValuesBy(v1, v1, { it.rating }, { it.name }) val diff = compareValuesBy(v1, v1, { it.rating }, { it.name })
assertTrue(diff == 0) assertTrue(diff == 0)
} }
Test fun compareNullables() { @Test
fun compareNullables() {
val v1: Item? = this.v1 val v1: Item? = this.v1
val v2: Item? = null val v2: Item? = null
val diff = compareValuesBy(v1, v2) { it?.rating } val diff = compareValuesBy(v1, v2) { it?.rating }
@@ -43,7 +48,8 @@ class OrderingTest {
assertTrue(diff2 < 0) assertTrue(diff2 < 0)
} }
Test fun sortComparatorThenComparator() { @Test
fun sortComparatorThenComparator() {
val comparator = comparator<Item> { a, b -> a.name.compareTo(b.name) } thenComparator { a, b -> a.rating.compareTo(b.rating) } val comparator = comparator<Item> { a, b -> a.name.compareTo(b.name) } thenComparator { a, b -> a.rating.compareTo(b.rating) }
val diff = comparator.compare(v1, v2) val diff = comparator.compare(v1, v2)
@@ -53,7 +59,8 @@ class OrderingTest {
assertEquals(v1, items[1]) assertEquals(v1, items[1])
} }
Test fun combineComparators() { @Test
fun combineComparators() {
val byName = compareBy<Item> { it.name } val byName = compareBy<Item> { it.name }
val byRating = compareBy<Item> { it.rating } val byRating = compareBy<Item> { it.rating }
val v3 = Item(v1.name, v1.rating + 1) val v3 = Item(v1.name, v1.rating + 1)
@@ -67,7 +74,8 @@ class OrderingTest {
assertTrue( (byRating thenDescending byName).compare(v4, v2) < 0 ) assertTrue( (byRating thenDescending byName).compare(v4, v2) < 0 )
} }
Test fun sortByThenBy() { @Test
fun sortByThenBy() {
val comparator = compareBy<Item> { it.rating } thenBy { it.name } val comparator = compareBy<Item> { it.rating } thenBy { it.name }
val diff = comparator.compare(v1, v2) val diff = comparator.compare(v1, v2)
@@ -77,7 +85,8 @@ class OrderingTest {
assertEquals(v2, items[1]) assertEquals(v2, items[1])
} }
Test fun sortByThenByDescending() { @Test
fun sortByThenByDescending() {
val comparator = compareBy<Item> { it.rating } thenByDescending { it.name } val comparator = compareBy<Item> { it.rating } thenByDescending { it.name }
val diff = comparator.compare(v1, v2) val diff = comparator.compare(v1, v2)
@@ -87,7 +96,8 @@ class OrderingTest {
assertEquals(v2, items[1]) assertEquals(v2, items[1])
} }
Test fun sortUsingFunctionalComparator() { @Test
fun sortUsingFunctionalComparator() {
val comparator = compareBy<Item>({ it.name }, { it.rating }) val comparator = compareBy<Item>({ it.name }, { it.rating })
val diff = comparator.compare(v1, v2) val diff = comparator.compare(v1, v2)
assertTrue(diff > 0) assertTrue(diff > 0)
@@ -96,7 +106,8 @@ class OrderingTest {
assertEquals(v1, items[1]) assertEquals(v1, items[1])
} }
Test fun sortUsingCustomComparator() { @Test
fun sortUsingCustomComparator() {
val comparator = object : Comparator<Item> { val comparator = object : Comparator<Item> {
override fun compare(o1: Item, o2: Item): Int { override fun compare(o1: Item, o2: Item): Int {
return compareValuesBy(o1, o2, { it.name }, { it.rating }) return compareValuesBy(o1, o2, { it.name }, { it.rating })
+21 -21
View File
@@ -5,7 +5,7 @@ import kotlin.test.*
class PreconditionsTest() { class PreconditionsTest() {
test fun passingRequire() { @test fun passingRequire() {
require(true) require(true)
var called = false var called = false
@@ -13,32 +13,32 @@ class PreconditionsTest() {
assertFalse(called) assertFalse(called)
} }
test fun failingRequire() { @test fun failingRequire() {
val error = assertFailsWith(IllegalArgumentException::class) { val error = assertFailsWith(IllegalArgumentException::class) {
require(false) require(false)
} }
assertNotNull(error.getMessage()) assertNotNull(error.getMessage())
} }
test fun passingRequireWithMessage() { @test fun passingRequireWithMessage() {
require(true, "Hello") require(true, "Hello")
} }
test fun failingRequireWithMessage() { @test fun failingRequireWithMessage() {
val error = assertFailsWith(IllegalArgumentException::class) { val error = assertFailsWith(IllegalArgumentException::class) {
require(false, "Hello") require(false, "Hello")
} }
assertEquals("Hello", error.getMessage()) assertEquals("Hello", error.getMessage())
} }
test fun failingRequireWithLazyMessage() { @test fun failingRequireWithLazyMessage() {
val error = assertFailsWith(IllegalArgumentException::class) { val error = assertFailsWith(IllegalArgumentException::class) {
require(false) { "Hello" } require(false) { "Hello" }
} }
assertEquals("Hello", error.getMessage()) assertEquals("Hello", error.getMessage())
} }
test fun passingCheck() { @test fun passingCheck() {
check(true) check(true)
var called = false var called = false
@@ -46,45 +46,45 @@ class PreconditionsTest() {
assertFalse(called) assertFalse(called)
} }
test fun failingCheck() { @test fun failingCheck() {
val error = assertFailsWith(IllegalStateException::class) { val error = assertFailsWith(IllegalStateException::class) {
check(false) check(false)
} }
assertNotNull(error.getMessage()) assertNotNull(error.getMessage())
} }
test fun passingCheckWithMessage() { @test fun passingCheckWithMessage() {
check(true, "Hello") check(true, "Hello")
} }
test fun failingCheckWithMessage() { @test fun failingCheckWithMessage() {
val error = assertFailsWith(IllegalStateException::class) { val error = assertFailsWith(IllegalStateException::class) {
check(false, "Hello") check(false, "Hello")
} }
assertEquals("Hello", error.getMessage()) assertEquals("Hello", error.getMessage())
} }
test fun failingCheckWithLazyMessage() { @test fun failingCheckWithLazyMessage() {
val error = assertFailsWith(IllegalStateException::class) { val error = assertFailsWith(IllegalStateException::class) {
check(false) { "Hello" } check(false) { "Hello" }
} }
assertEquals("Hello", error.getMessage()) assertEquals("Hello", error.getMessage())
} }
test fun requireNotNull() { @test fun requireNotNull() {
val s1: String? = "S1" val s1: String? = "S1"
val r1: String = requireNotNull(s1) val r1: String = requireNotNull(s1)
assertEquals("S1", r1) assertEquals("S1", r1)
} }
test fun requireNotNullFails() { @test fun requireNotNullFails() {
assertFailsWith(IllegalArgumentException::class) { assertFailsWith(IllegalArgumentException::class) {
val s2: String? = null val s2: String? = null
requireNotNull(s2) requireNotNull(s2)
} }
} }
test fun requireNotNullWithLazyMessage() { @test fun requireNotNullWithLazyMessage() {
val error = assertFailsWith(IllegalArgumentException::class) { val error = assertFailsWith(IllegalArgumentException::class) {
val obj: Any? = null val obj: Any? = null
requireNotNull(obj) { "Message" } requireNotNull(obj) { "Message" }
@@ -99,20 +99,20 @@ class PreconditionsTest() {
assertFalse(lazyCalled, "Message is not evaluated if the condition is met") assertFalse(lazyCalled, "Message is not evaluated if the condition is met")
} }
test fun checkNotNull() { @test fun checkNotNull() {
val s1: String? = "S1" val s1: String? = "S1"
val r1: String = checkNotNull(s1) val r1: String = checkNotNull(s1)
assertEquals("S1", r1) assertEquals("S1", r1)
} }
test fun checkNotNullFails() { @test fun checkNotNullFails() {
assertFailsWith(IllegalStateException::class) { assertFailsWith(IllegalStateException::class) {
val s2: String? = null val s2: String? = null
checkNotNull(s2) checkNotNull(s2)
} }
} }
test fun passingAssert() { @test fun passingAssert() {
assert(true) assert(true)
var called = false var called = false
assert(true) { called = true; "some message" } assert(true) { called = true; "some message" }
@@ -121,7 +121,7 @@ class PreconditionsTest() {
} }
test fun failingAssert() { @test fun failingAssert() {
val error = assertFails { val error = assertFails {
assert(false) assert(false)
} }
@@ -132,7 +132,7 @@ class PreconditionsTest() {
} }
} }
test fun error() { @test fun error() {
val error = assertFails { val error = assertFails {
error("There was a problem") error("There was a problem")
} }
@@ -143,11 +143,11 @@ class PreconditionsTest() {
} }
} }
test fun passingAssertWithMessage() { @test fun passingAssertWithMessage() {
assert(true, "Hello") assert(true, "Hello")
} }
test fun failingAssertWithMessage() { @test fun failingAssertWithMessage() {
val error = assertFails { val error = assertFails {
assert(false, "Hello") assert(false, "Hello")
} }
@@ -158,7 +158,7 @@ class PreconditionsTest() {
} }
} }
test fun failingAssertWithLazyMessage() { @test fun failingAssertWithLazyMessage() {
val error = assertFails { val error = assertFails {
assert(false) { "Hello" } assert(false) { "Hello" }
} }
+1 -1
View File
@@ -9,7 +9,7 @@ private fun listDifference<T>(first : List<T>, second : List<T>) : List<T> {
class StdLibIssuesTest { class StdLibIssuesTest {
test fun test_KT_1131() { @test fun test_KT_1131() {
val data = arrayListOf("blah", "foo", "bar") val data = arrayListOf("blah", "foo", "bar")
val filterValues = arrayListOf("bar", "something", "blah") val filterValues = arrayListOf("bar", "something", "blah")
+14 -14
View File
@@ -8,22 +8,22 @@ import kotlin.test.assertNotEquals
class PairTest { class PairTest {
val p = Pair(1, "a") val p = Pair(1, "a")
test fun pairFirstAndSecond() { @test fun pairFirstAndSecond() {
assertEquals(1, p.first) assertEquals(1, p.first)
assertEquals("a", p.second) assertEquals("a", p.second)
} }
test fun pairMultiAssignment() { @test fun pairMultiAssignment() {
val (a, b) = p val (a, b) = p
assertEquals(1, a) assertEquals(1, a)
assertEquals("a", b) assertEquals("a", b)
} }
test fun pairToString() { @test fun pairToString() {
assertEquals("(1, a)", p.toString()) assertEquals("(1, a)", p.toString())
} }
test fun pairEquals() { @test fun pairEquals() {
assertEquals(Pair(1, "a"), p) assertEquals(Pair(1, "a"), p)
assertNotEquals(Pair(2, "a"), p) assertNotEquals(Pair(2, "a"), p)
assertNotEquals(Pair(1, "b"), p) assertNotEquals(Pair(1, "b"), p)
@@ -31,7 +31,7 @@ class PairTest {
assertNotEquals("", (p : Any)) assertNotEquals("", (p : Any))
} }
test fun pairHashCode() { @test fun pairHashCode() {
assertEquals(Pair(1, "a").hashCode(), p.hashCode()) assertEquals(Pair(1, "a").hashCode(), p.hashCode())
assertNotEquals(Pair(2, "a").hashCode(), p.hashCode()) assertNotEquals(Pair(2, "a").hashCode(), p.hashCode())
assertNotEquals(0, Pair(null, "b").hashCode()) assertNotEquals(0, Pair(null, "b").hashCode())
@@ -39,13 +39,13 @@ class PairTest {
assertEquals(0, Pair(null, null).hashCode()) assertEquals(0, Pair(null, null).hashCode())
} }
test fun pairHashSet() { @test fun pairHashSet() {
val s = hashSetOf(Pair(1, "a"), Pair(1, "b"), Pair(1, "a")) val s = hashSetOf(Pair(1, "a"), Pair(1, "b"), Pair(1, "a"))
assertEquals(2, s.size()) assertEquals(2, s.size())
assertTrue(s.contains(p)) assertTrue(s.contains(p))
} }
test fun pairToList() { @test fun pairToList() {
assertEquals(listOf(1, 2), (1 to 2).toList()) assertEquals(listOf(1, 2), (1 to 2).toList())
assertEquals(listOf(1, null), (1 to null).toList()) assertEquals(listOf(1, null), (1 to null).toList())
assertEquals(listOf(1, "2"), (1 to "2").toList()) assertEquals(listOf(1, "2"), (1 to "2").toList())
@@ -55,24 +55,24 @@ class PairTest {
class TripleTest { class TripleTest {
val t = Triple(1, "a", 0.07) val t = Triple(1, "a", 0.07)
test fun tripleFirstAndSecond() { @test fun tripleFirstAndSecond() {
assertEquals(1, t.first) assertEquals(1, t.first)
assertEquals("a", t.second) assertEquals("a", t.second)
assertEquals(0.07, t.third) assertEquals(0.07, t.third)
} }
test fun tripleMultiAssignment() { @test fun tripleMultiAssignment() {
val (a, b, c) = t val (a, b, c) = t
assertEquals(1, a) assertEquals(1, a)
assertEquals("a", b) assertEquals("a", b)
assertEquals(0.07, c) assertEquals(0.07, c)
} }
test fun tripleToString() { @test fun tripleToString() {
assertEquals("(1, a, 0.07)", t.toString()) assertEquals("(1, a, 0.07)", t.toString())
} }
test fun tripleEquals() { @test fun tripleEquals() {
assertEquals(Triple(1, "a", 0.07), t) assertEquals(Triple(1, "a", 0.07), t)
assertNotEquals(Triple(2, "a", 0.07), t) assertNotEquals(Triple(2, "a", 0.07), t)
assertNotEquals(Triple(1, "b", 0.07), t) assertNotEquals(Triple(1, "b", 0.07), t)
@@ -81,7 +81,7 @@ class TripleTest {
assertNotEquals("", (t : Any)) assertNotEquals("", (t : Any))
} }
test fun tripleHashCode() { @test fun tripleHashCode() {
assertEquals(Triple(1, "a", 0.07).hashCode(), t.hashCode()) assertEquals(Triple(1, "a", 0.07).hashCode(), t.hashCode())
assertNotEquals(Triple(2, "a", 0.07).hashCode(), t.hashCode()) assertNotEquals(Triple(2, "a", 0.07).hashCode(), t.hashCode())
assertNotEquals(0, Triple(null, "b", 0.07).hashCode()) assertNotEquals(0, Triple(null, "b", 0.07).hashCode())
@@ -90,13 +90,13 @@ class TripleTest {
assertEquals(0, Triple(null, null, null).hashCode()) assertEquals(0, Triple(null, null, null).hashCode())
} }
test fun tripleHashSet() { @test fun tripleHashSet() {
val s = hashSetOf(Triple(1, "a", 0.07), Triple(1, "b", 0.07), Triple(1, "a", 0.07)) val s = hashSetOf(Triple(1, "a", 0.07), Triple(1, "b", 0.07), Triple(1, "a", 0.07))
assertEquals(2, s.size()) assertEquals(2, s.size())
assertTrue(s.contains(t)) assertTrue(s.contains(t))
} }
test fun tripleToList() { @test fun tripleToList() {
assertEquals(listOf(1, 2, 3), (Triple(1, 2, 3)).toList()) assertEquals(listOf(1, 2, 3), (Triple(1, 2, 3)).toList())
assertEquals(listOf(1, null, 3), (Triple(1, null, 3)).toList()) assertEquals(listOf(1, null, 3), (Triple(1, null, 3)).toList())
assertEquals(listOf(1, 2, "3"), (Triple(1, 2, "3")).toList()) assertEquals(listOf(1, 2, "3"), (Triple(1, 2, "3")).toList())
+1 -1
View File
@@ -8,7 +8,7 @@ import org.junit.Test as test
class BrowserTest { class BrowserTest {
test fun accessBrowserDOM() { @test fun accessBrowserDOM() {
registerBrowserPage() registerBrowserPage()
val h1 = document["h1"].first() val h1 = document["h1"].first()
@@ -5,7 +5,7 @@ import org.junit.Test as test
class ArraysJVMTest { class ArraysJVMTest {
test fun orEmptyNull() { @test fun orEmptyNull() {
val x: Array<String>? = null val x: Array<String>? = null
val y: Array<out String>? = null val y: Array<out String>? = null
val xArray = x.orEmpty() val xArray = x.orEmpty()
@@ -14,7 +14,7 @@ class ArraysJVMTest {
expect(0) { yArray.size() } expect(0) { yArray.size() }
} }
test fun orEmptyNotNull() { @test fun orEmptyNotNull() {
val x: Array<String>? = arrayOf("1", "2") val x: Array<String>? = arrayOf("1", "2")
val xArray = x.orEmpty() val xArray = x.orEmpty()
expect(2) { xArray.size() } expect(2) { xArray.size() }
+67 -67
View File
@@ -17,7 +17,7 @@ fun assertArrayNotSameButEquals(expected: BooleanArray, actual: BooleanArray, me
class ArraysTest { class ArraysTest {
test fun emptyArrayLastIndex() { @test fun emptyArrayLastIndex() {
val arr1 = IntArray(0) val arr1 = IntArray(0)
assertEquals(-1, arr1.lastIndex) assertEquals(-1, arr1.lastIndex)
@@ -25,7 +25,7 @@ class ArraysTest {
assertEquals(-1, arr2.lastIndex) assertEquals(-1, arr2.lastIndex)
} }
test fun arrayLastIndex() { @test fun arrayLastIndex() {
val arr1 = intArrayOf(0, 1, 2, 3, 4) val arr1 = intArrayOf(0, 1, 2, 3, 4)
assertEquals(4, arr1.lastIndex) assertEquals(4, arr1.lastIndex)
assertEquals(4, arr1[arr1.lastIndex]) assertEquals(4, arr1[arr1.lastIndex])
@@ -35,7 +35,7 @@ class ArraysTest {
assertEquals("4", arr2[arr2.lastIndex]) assertEquals("4", arr2[arr2.lastIndex])
} }
test fun byteArray() { @test fun byteArray() {
val arr = ByteArray(2) val arr = ByteArray(2)
val expected: Byte = 0 val expected: Byte = 0
@@ -44,7 +44,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
test fun shortArray() { @test fun shortArray() {
val arr = ShortArray(2) val arr = ShortArray(2)
val expected: Short = 0 val expected: Short = 0
@@ -53,7 +53,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
test fun intArray() { @test fun intArray() {
val arr = IntArray(2) val arr = IntArray(2)
assertEquals(arr.size(), 2) assertEquals(arr.size(), 2)
@@ -61,7 +61,7 @@ class ArraysTest {
assertEquals(0, arr[1]) assertEquals(0, arr[1])
} }
test fun longArray() { @test fun longArray() {
val arr = LongArray(2) val arr = LongArray(2)
val expected: Long = 0 val expected: Long = 0
@@ -70,7 +70,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
test fun floatArray() { @test fun floatArray() {
val arr = FloatArray(2) val arr = FloatArray(2)
val expected: Float = 0.0F val expected: Float = 0.0F
@@ -79,7 +79,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
test fun doubleArray() { @test fun doubleArray() {
val arr = DoubleArray(2) val arr = DoubleArray(2)
assertEquals(arr.size(), 2) assertEquals(arr.size(), 2)
@@ -87,7 +87,7 @@ class ArraysTest {
assertEquals(0.0, arr[1]) assertEquals(0.0, arr[1])
} }
test fun charArray() { @test fun charArray() {
val arr = CharArray(2) val arr = CharArray(2)
val expected: Char = '\u0000' val expected: Char = '\u0000'
@@ -96,14 +96,14 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
test fun booleanArray() { @test fun booleanArray() {
val arr = BooleanArray(2) val arr = BooleanArray(2)
assertEquals(arr.size(), 2) assertEquals(arr.size(), 2)
assertEquals(false, arr[0]) assertEquals(false, arr[0])
assertEquals(false, arr[1]) assertEquals(false, arr[1])
} }
test fun min() { @test fun min() {
expect(null, { arrayOf<Int>().min() }) expect(null, { arrayOf<Int>().min() })
expect(1, { arrayOf(1).min() }) expect(1, { arrayOf(1).min() })
expect(2, { arrayOf(2, 3).min() }) expect(2, { arrayOf(2, 3).min() })
@@ -112,7 +112,7 @@ class ArraysTest {
expect("a", { arrayOf("a", "b").min() }) expect("a", { arrayOf("a", "b").min() })
} }
test fun minInPrimitiveArrays() { @test fun minInPrimitiveArrays() {
expect(null, { intArrayOf().min() }) expect(null, { intArrayOf().min() })
expect(1, { intArrayOf(1).min() }) expect(1, { intArrayOf(1).min() })
expect(2, { intArrayOf(2, 3).min() }) expect(2, { intArrayOf(2, 3).min() })
@@ -124,7 +124,7 @@ class ArraysTest {
expect('a', { charArrayOf('a', 'b').min() }) expect('a', { charArrayOf('a', 'b').min() })
} }
test fun max() { @test fun max() {
expect(null, { arrayOf<Int>().max() }) expect(null, { arrayOf<Int>().max() })
expect(1, { arrayOf(1).max() }) expect(1, { arrayOf(1).max() })
expect(3, { arrayOf(2, 3).max() }) expect(3, { arrayOf(2, 3).max() })
@@ -133,7 +133,7 @@ class ArraysTest {
expect("b", { arrayOf("a", "b").max() }) expect("b", { arrayOf("a", "b").max() })
} }
test fun maxInPrimitiveArrays() { @test fun maxInPrimitiveArrays() {
expect(null, { intArrayOf().max() }) expect(null, { intArrayOf().max() })
expect(1, { intArrayOf(1).max() }) expect(1, { intArrayOf(1).max() })
expect(3, { intArrayOf(2, 3).max() }) expect(3, { intArrayOf(2, 3).max() })
@@ -145,7 +145,7 @@ class ArraysTest {
expect('b', { charArrayOf('a', 'b').max() }) expect('b', { charArrayOf('a', 'b').max() })
} }
test fun minBy() { @test fun minBy() {
expect(null, { arrayOf<Int>().minBy { it } }) expect(null, { arrayOf<Int>().minBy { it } })
expect(1, { arrayOf(1).minBy { it } }) expect(1, { arrayOf(1).minBy { it } })
expect(3, { arrayOf(2, 3).minBy { -it } }) expect(3, { arrayOf(2, 3).minBy { -it } })
@@ -153,7 +153,7 @@ class ArraysTest {
expect("b", { arrayOf("b", "abc").minBy { it.length() } }) expect("b", { arrayOf("b", "abc").minBy { it.length() } })
} }
test fun minByInPrimitiveArrays() { @test fun minByInPrimitiveArrays() {
expect(null, { intArrayOf().minBy { it } }) expect(null, { intArrayOf().minBy { it } })
expect(1, { intArrayOf(1).minBy { it } }) expect(1, { intArrayOf(1).minBy { it } })
expect(3, { intArrayOf(2, 3).minBy { -it } }) expect(3, { intArrayOf(2, 3).minBy { -it } })
@@ -164,7 +164,7 @@ class ArraysTest {
expect(2.0, { doubleArrayOf(2.0, 3.0).minBy { Math.sqrt(it) } }) expect(2.0, { doubleArrayOf(2.0, 3.0).minBy { Math.sqrt(it) } })
} }
test fun maxBy() { @test fun maxBy() {
expect(null, { arrayOf<Int>().maxBy { it } }) expect(null, { arrayOf<Int>().maxBy { it } })
expect(1, { arrayOf(1).maxBy { it } }) expect(1, { arrayOf(1).maxBy { it } })
expect(2, { arrayOf(2, 3).maxBy { -it } }) expect(2, { arrayOf(2, 3).maxBy { -it } })
@@ -172,7 +172,7 @@ class ArraysTest {
expect("abc", { arrayOf("b", "abc").maxBy { it.length() } }) expect("abc", { arrayOf("b", "abc").maxBy { it.length() } })
} }
test fun maxByInPrimitiveArrays() { @test fun maxByInPrimitiveArrays() {
expect(null, { intArrayOf().maxBy { it } }) expect(null, { intArrayOf().maxBy { it } })
expect(1, { intArrayOf(1).maxBy { it } }) expect(1, { intArrayOf(1).maxBy { it } })
expect(2, { intArrayOf(2, 3).maxBy { -it } }) expect(2, { intArrayOf(2, 3).maxBy { -it } })
@@ -183,29 +183,29 @@ class ArraysTest {
expect(3.0, { doubleArrayOf(2.0, 3.0).maxBy { Math.sqrt(it) } }) expect(3.0, { doubleArrayOf(2.0, 3.0).maxBy { Math.sqrt(it) } })
} }
test fun minIndex() { @test fun minIndex() {
val a = intArrayOf(1, 7, 9, -42, 54, 93) val a = intArrayOf(1, 7, 9, -42, 54, 93)
expect(3, { a.indices.minBy { a[it] } }) expect(3, { a.indices.minBy { a[it] } })
} }
test fun maxIndex() { @test fun maxIndex() {
val a = intArrayOf(1, 7, 9, 239, 54, 93) val a = intArrayOf(1, 7, 9, 239, 54, 93)
expect(3, { a.indices.maxBy { a[it] } }) expect(3, { a.indices.maxBy { a[it] } })
} }
test fun minByEvaluateOnce() { @test fun minByEvaluateOnce() {
var c = 0 var c = 0
expect(1, { arrayOf(5, 4, 3, 2, 1).minBy { c++; it * it } }) expect(1, { arrayOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
} }
test fun maxByEvaluateOnce() { @test fun maxByEvaluateOnce() {
var c = 0 var c = 0
expect(5, { arrayOf(5, 4, 3, 2, 1).maxBy { c++; it * it } }) expect(5, { arrayOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
} }
test fun sum() { @test fun sum() {
expect(0) { arrayOf<Int>().sum() } expect(0) { arrayOf<Int>().sum() }
expect(14) { arrayOf(2, 3, 9).sum() } expect(14) { arrayOf(2, 3, 9).sum() }
expect(3.0) { arrayOf(1.0, 2.0).sum() } expect(3.0) { arrayOf(1.0, 2.0).sum() }
@@ -215,7 +215,7 @@ class ArraysTest {
expect(3.0F) { arrayOf<Float>(1.0F, 2.0F).sum() } expect(3.0F) { arrayOf<Float>(1.0F, 2.0F).sum() }
} }
test fun sumInPrimitiveArrays() { @test fun sumInPrimitiveArrays() {
expect(0) { intArrayOf().sum() } expect(0) { intArrayOf().sum() }
expect(14) { intArrayOf(2, 3, 9).sum() } expect(14) { intArrayOf(2, 3, 9).sum() }
expect(3.0) { doubleArrayOf(1.0, 2.0).sum() } expect(3.0) { doubleArrayOf(1.0, 2.0).sum() }
@@ -225,7 +225,7 @@ class ArraysTest {
expect(3.0F) { floatArrayOf(1.0F, 2.0F).sum() } expect(3.0F) { floatArrayOf(1.0F, 2.0F).sum() }
} }
test fun average() { @test fun average() {
expect(0.0) { arrayOf<Int>().average() } expect(0.0) { arrayOf<Int>().average() }
expect(3.8) { arrayOf(1, 2, 5, 8, 3).average() } expect(3.8) { arrayOf(1, 2, 5, 8, 3).average() }
expect(2.1) { arrayOf(1.6, 2.6, 3.6, 0.6).average() } expect(2.1) { arrayOf(1.6, 2.6, 3.6, 0.6).average() }
@@ -236,7 +236,7 @@ class ArraysTest {
// for each arr with size > 0 arr.average() = arr.sum().toDouble() / arr.size() // for each arr with size > 0 arr.average() = arr.sum().toDouble() / arr.size()
} }
test fun indexOfInPrimitiveArrays() { @test fun indexOfInPrimitiveArrays() {
expect(-1) { byteArrayOf(1, 2, 3) indexOf 0 } expect(-1) { byteArrayOf(1, 2, 3) indexOf 0 }
expect(0) { byteArrayOf(1, 2, 3) indexOf 1 } expect(0) { byteArrayOf(1, 2, 3) indexOf 1 }
expect(1) { byteArrayOf(1, 2, 3) indexOf 2 } expect(1) { byteArrayOf(1, 2, 3) indexOf 2 }
@@ -277,7 +277,7 @@ class ArraysTest {
expect(-1) { booleanArrayOf(true) indexOf false } expect(-1) { booleanArrayOf(true) indexOf false }
} }
test fun indexOf() { @test fun indexOf() {
expect(-1) { arrayOf("cat", "dog", "bird").indexOf("mouse") } expect(-1) { arrayOf("cat", "dog", "bird").indexOf("mouse") }
expect(0) { arrayOf("cat", "dog", "bird").indexOf("cat") } expect(0) { arrayOf("cat", "dog", "bird").indexOf("cat") }
expect(1) { arrayOf("cat", "dog", "bird").indexOf("dog") } expect(1) { arrayOf("cat", "dog", "bird").indexOf("dog") }
@@ -295,7 +295,7 @@ class ArraysTest {
expect(2) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.endsWith('d') } } expect(2) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.endsWith('d') } }
} }
test fun lastIndexOf() { @test fun lastIndexOf() {
expect(-1) { arrayOf("cat", "dog", "bird").lastIndexOf("mouse") } expect(-1) { arrayOf("cat", "dog", "bird").lastIndexOf("mouse") }
expect(0) { arrayOf("cat", "dog", "bird").lastIndexOf("cat") } expect(0) { arrayOf("cat", "dog", "bird").lastIndexOf("cat") }
expect(1) { arrayOf("cat", "dog", "bird").lastIndexOf("dog") } expect(1) { arrayOf("cat", "dog", "bird").lastIndexOf("dog") }
@@ -315,7 +315,7 @@ class ArraysTest {
expect(3) { sequenceOf("cat", "dog", "bird", "red").indexOfLast { it.endsWith('d') } } expect(3) { sequenceOf("cat", "dog", "bird", "red").indexOfLast { it.endsWith('d') } }
} }
test fun isEmpty() { @test fun isEmpty() {
assertTrue(emptyArray<String>().isEmpty()) assertTrue(emptyArray<String>().isEmpty())
assertFalse(arrayOf("").isEmpty()) assertFalse(arrayOf("").isEmpty())
assertTrue(intArrayOf().isEmpty()) assertTrue(intArrayOf().isEmpty())
@@ -336,12 +336,12 @@ class ArraysTest {
assertFalse(booleanArrayOf(false).isEmpty()) assertFalse(booleanArrayOf(false).isEmpty())
} }
test fun isNotEmpty() { @test fun isNotEmpty() {
assertFalse(intArrayOf().isNotEmpty()) assertFalse(intArrayOf().isNotEmpty())
assertTrue(intArrayOf(1).isNotEmpty()) assertTrue(intArrayOf(1).isNotEmpty())
} }
test fun plus() { @test fun plus() {
assertEquals(listOf("1", "2", "3", "4"), listOf("1", "2") + arrayOf("3", "4")) assertEquals(listOf("1", "2", "3", "4"), listOf("1", "2") + arrayOf("3", "4"))
assertArrayNotSameButEquals(arrayOf("1", "2", "3"), arrayOf("1", "2") + "3") assertArrayNotSameButEquals(arrayOf("1", "2", "3"), arrayOf("1", "2") + "3")
assertArrayNotSameButEquals(arrayOf("1", "2", "3", "4"), arrayOf("1", "2") + arrayOf("3", "4")) assertArrayNotSameButEquals(arrayOf("1", "2", "3", "4"), arrayOf("1", "2") + arrayOf("3", "4"))
@@ -351,7 +351,7 @@ class ArraysTest {
assertArrayNotSameButEquals(intArrayOf(1, 2, 3, 4), intArrayOf(1, 2) + intArrayOf(3, 4)) assertArrayNotSameButEquals(intArrayOf(1, 2, 3, 4), intArrayOf(1, 2) + intArrayOf(3, 4))
} }
test fun plusVararg() { @test fun plusVararg() {
fun stringOnePlus(vararg a: String) = arrayOf("1") + a fun stringOnePlus(vararg a: String) = arrayOf("1") + a
fun longOnePlus(vararg a: Long) = longArrayOf(1) + a fun longOnePlus(vararg a: Long) = longArrayOf(1) + a
fun intOnePlus(vararg a: Int) = intArrayOf(1) + a fun intOnePlus(vararg a: Int) = intArrayOf(1) + a
@@ -361,7 +361,7 @@ class ArraysTest {
assertArrayNotSameButEquals(longArrayOf(1, 2), longOnePlus(2), "LongArray.plus") assertArrayNotSameButEquals(longArrayOf(1, 2), longOnePlus(2), "LongArray.plus")
} }
test fun plusAssign() { @test fun plusAssign() {
// lets use a mutable variable // lets use a mutable variable
var result = arrayOf("a") var result = arrayOf("a")
result += "foo" result += "foo"
@@ -370,23 +370,23 @@ class ArraysTest {
assertArrayNotSameButEquals(arrayOf("a", "foo", "beer", "cheese", "wine"), result) assertArrayNotSameButEquals(arrayOf("a", "foo", "beer", "cheese", "wine"), result)
} }
test fun first() { @test fun first() {
expect(1) { arrayOf(1, 2, 3).first() } expect(1) { arrayOf(1, 2, 3).first() }
expect(2) { arrayOf(1, 2, 3).first { it % 2 == 0 } } expect(2) { arrayOf(1, 2, 3).first { it % 2 == 0 } }
} }
test fun last() { @test fun last() {
expect(3) { arrayOf(1, 2, 3).last() } expect(3) { arrayOf(1, 2, 3).last() }
expect(2) { arrayOf(1, 2, 3).last { it % 2 == 0 } } expect(2) { arrayOf(1, 2, 3).last { it % 2 == 0 } }
} }
test fun contains() { @test fun contains() {
assertTrue(arrayOf("1", "2", "3", "4").contains("2")) assertTrue(arrayOf("1", "2", "3", "4").contains("2"))
assertTrue("3" in arrayOf("1", "2", "3", "4")) assertTrue("3" in arrayOf("1", "2", "3", "4"))
assertTrue("0" !in arrayOf("1", "2", "3", "4")) assertTrue("0" !in arrayOf("1", "2", "3", "4"))
} }
test fun slice() { @test fun slice() {
val iter: Iterable<Int> = listOf(3, 1, 2) val iter: Iterable<Int> = listOf(3, 1, 2)
assertEquals(listOf("B"), arrayOf("A", "B", "C").slice(1..1)) assertEquals(listOf("B"), arrayOf("A", "B", "C").slice(1..1))
@@ -403,7 +403,7 @@ class ArraysTest {
assertEquals(listOf(true, false, true), booleanArrayOf(true, false, true, true).slice(iter)) assertEquals(listOf(true, false, true), booleanArrayOf(true, false, true, true).slice(iter))
} }
test fun sliceArray() { @test fun sliceArray() {
val coll: Collection<Int> = listOf(3, 1, 2) val coll: Collection<Int> = listOf(3, 1, 2)
assertArrayNotSameButEquals(arrayOf("B"), arrayOf("A", "B", "C").sliceArray(1..1)) assertArrayNotSameButEquals(arrayOf("B"), arrayOf("A", "B", "C").sliceArray(1..1))
@@ -420,7 +420,7 @@ class ArraysTest {
assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).sliceArray(coll)) assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).sliceArray(coll))
} }
test fun asIterable() { @test fun asIterable() {
val arr1 = intArrayOf(1, 2, 3, 4, 5) val arr1 = intArrayOf(1, 2, 3, 4, 5)
val iter1 = arr1.asIterable() val iter1 = arr1.asIterable()
assertEquals(arr1.toList(), iter1.toList()) assertEquals(arr1.toList(), iter1.toList())
@@ -442,7 +442,7 @@ class ArraysTest {
assertEquals(iter4.toList(), emptyList<String>()) assertEquals(iter4.toList(), emptyList<String>())
} }
test fun asList() { @test fun asList() {
assertEquals(listOf(1, 2, 3), intArrayOf(1, 2, 3).asList()) assertEquals(listOf(1, 2, 3), intArrayOf(1, 2, 3).asList())
assertEquals(listOf<Byte>(1, 2, 3), byteArrayOf(1, 2, 3).asList()) assertEquals(listOf<Byte>(1, 2, 3), byteArrayOf(1, 2, 3).asList())
assertEquals(listOf(true, false), booleanArrayOf(true, false).asList()) assertEquals(listOf(true, false), booleanArrayOf(true, false).asList())
@@ -457,7 +457,7 @@ class ArraysTest {
assertEquals(10, intsAsList[1], "Should reflect changes in original array") assertEquals(10, intsAsList[1], "Should reflect changes in original array")
} }
test fun toPrimitiveArray() { @test fun toPrimitiveArray() {
val genericArray: Array<Int> = arrayOf(1, 2, 3) val genericArray: Array<Int> = arrayOf(1, 2, 3)
val primitiveArray: IntArray = genericArray.toIntArray() val primitiveArray: IntArray = genericArray.toIntArray()
expect(3) { primitiveArray.size() } expect(3) { primitiveArray.size() }
@@ -469,14 +469,14 @@ class ArraysTest {
assertEquals(charList, charArray.asList()) assertEquals(charList, charArray.asList())
} }
test fun toTypedArray() { @test fun toTypedArray() {
val primitiveArray: LongArray = longArrayOf(1, 2, Long.MAX_VALUE) val primitiveArray: LongArray = longArrayOf(1, 2, Long.MAX_VALUE)
val genericArray: Array<Long> = primitiveArray.toTypedArray() val genericArray: Array<Long> = primitiveArray.toTypedArray()
expect(3) { genericArray.size() } expect(3) { genericArray.size() }
assertEquals(primitiveArray.asList(), genericArray.asList()) assertEquals(primitiveArray.asList(), genericArray.asList())
} }
test fun copyOf() { @test fun copyOf() {
booleanArrayOf(true, false, true).let { assertArrayNotSameButEquals(it, it.copyOf()) } booleanArrayOf(true, false, true).let { assertArrayNotSameButEquals(it, it.copyOf()) }
byteArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } byteArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) }
shortArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } shortArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) }
@@ -487,7 +487,7 @@ class ArraysTest {
charArrayOf('0', '1', '2', '3', '4', '5').let { assertArrayNotSameButEquals(it, it.copyOf()) } charArrayOf('0', '1', '2', '3', '4', '5').let { assertArrayNotSameButEquals(it, it.copyOf()) }
} }
test fun copyAndResize() { @test fun copyAndResize() {
assertArrayNotSameButEquals(arrayOf("1", "2"), arrayOf("1", "2", "3").copyOf(2)) assertArrayNotSameButEquals(arrayOf("1", "2"), arrayOf("1", "2", "3").copyOf(2))
assertArrayNotSameButEquals(arrayOf("1", "2", null), arrayOf("1", "2").copyOf(3)) assertArrayNotSameButEquals(arrayOf("1", "2", null), arrayOf("1", "2").copyOf(3))
@@ -501,7 +501,7 @@ class ArraysTest {
assertArrayNotSameButEquals(charArrayOf('A', 'B', '\u0000'), charArrayOf('A', 'B').copyOf(3)) assertArrayNotSameButEquals(charArrayOf('A', 'B', '\u0000'), charArrayOf('A', 'B').copyOf(3))
} }
test fun copyOfRange() { @test fun copyOfRange() {
assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).copyOfRange(0, 3)) assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).copyOfRange(0, 3))
assertArrayNotSameButEquals(byteArrayOf(0, 1, 2), byteArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3)) assertArrayNotSameButEquals(byteArrayOf(0, 1, 2), byteArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3))
assertArrayNotSameButEquals(shortArrayOf(0, 1, 2), shortArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3)) assertArrayNotSameButEquals(shortArrayOf(0, 1, 2), shortArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3))
@@ -514,7 +514,7 @@ class ArraysTest {
test fun reduce() { @test fun reduce() {
expect(-4) { intArrayOf(1, 2, 3) reduce { a, b -> a - b } } expect(-4) { intArrayOf(1, 2, 3) reduce { a, b -> a - b } }
expect(-4.toLong()) { longArrayOf(1, 2, 3) reduce { a, b -> a - b } } expect(-4.toLong()) { longArrayOf(1, 2, 3) reduce { a, b -> a - b } }
expect(-4F) { floatArrayOf(1F, 2F, 3F) reduce { a, b -> a - b } } expect(-4F) { floatArrayOf(1F, 2F, 3F) reduce { a, b -> a - b } }
@@ -530,7 +530,7 @@ class ArraysTest {
} is UnsupportedOperationException) } is UnsupportedOperationException)
} }
test fun reduceRight() { @test fun reduceRight() {
expect(2) { intArrayOf(1, 2, 3) reduceRight { a, b -> a - b } } expect(2) { intArrayOf(1, 2, 3) reduceRight { a, b -> a - b } }
expect(2.toLong()) { longArrayOf(1, 2, 3) reduceRight { a, b -> a - b } } expect(2.toLong()) { longArrayOf(1, 2, 3) reduceRight { a, b -> a - b } }
expect(2F) { floatArrayOf(1F, 2F, 3F) reduceRight { a, b -> a - b } } expect(2F) { floatArrayOf(1F, 2F, 3F) reduceRight { a, b -> a - b } }
@@ -546,7 +546,7 @@ class ArraysTest {
} is UnsupportedOperationException) } is UnsupportedOperationException)
} }
test fun reversed() { @test fun reversed() {
expect(listOf(3, 2, 1)) { intArrayOf(1, 2, 3).reversed() } expect(listOf(3, 2, 1)) { intArrayOf(1, 2, 3).reversed() }
expect(listOf<Byte>(3, 2, 1)) { byteArrayOf(1, 2, 3).reversed() } expect(listOf<Byte>(3, 2, 1)) { byteArrayOf(1, 2, 3).reversed() }
expect(listOf<Short>(3, 2, 1)) { shortArrayOf(1, 2, 3).reversed() } expect(listOf<Short>(3, 2, 1)) { shortArrayOf(1, 2, 3).reversed() }
@@ -557,7 +557,7 @@ class ArraysTest {
expect(listOf(false, false, true)) { booleanArrayOf(true, false, false).reversed() } expect(listOf(false, false, true)) { booleanArrayOf(true, false, false).reversed() }
} }
test fun reversedArray() { @test fun reversedArray() {
assertArrayNotSameButEquals(intArrayOf(3, 2, 1), intArrayOf(1, 2, 3).reversedArray()) assertArrayNotSameButEquals(intArrayOf(3, 2, 1), intArrayOf(1, 2, 3).reversedArray())
assertArrayNotSameButEquals(byteArrayOf(3, 2, 1), byteArrayOf(1, 2, 3).reversedArray()) assertArrayNotSameButEquals(byteArrayOf(3, 2, 1), byteArrayOf(1, 2, 3).reversedArray())
assertArrayNotSameButEquals(shortArrayOf(3, 2, 1), shortArrayOf(1, 2, 3).reversedArray()) assertArrayNotSameButEquals(shortArrayOf(3, 2, 1), shortArrayOf(1, 2, 3).reversedArray())
@@ -568,7 +568,7 @@ class ArraysTest {
assertArrayNotSameButEquals(booleanArrayOf(false, false, true), booleanArrayOf(true, false, false).reversedArray()) assertArrayNotSameButEquals(booleanArrayOf(false, false, true), booleanArrayOf(true, false, false).reversedArray())
} }
test fun drop() { @test fun drop() {
expect(listOf(1), { intArrayOf(1).drop(0) }) expect(listOf(1), { intArrayOf(1).drop(0) })
expect(listOf(), { intArrayOf().drop(1) }) expect(listOf(), { intArrayOf().drop(1) })
expect(listOf(), { intArrayOf(1).drop(1) }) expect(listOf(), { intArrayOf(1).drop(1) })
@@ -586,7 +586,7 @@ class ArraysTest {
} }
} }
test fun dropLast() { @test fun dropLast() {
expect(listOf(), { intArrayOf().dropLast(1) }) expect(listOf(), { intArrayOf().dropLast(1) })
expect(listOf(), { intArrayOf(1).dropLast(1) }) expect(listOf(), { intArrayOf(1).dropLast(1) })
expect(listOf(1), { intArrayOf(1).dropLast(0) }) expect(listOf(1), { intArrayOf(1).dropLast(0) })
@@ -604,7 +604,7 @@ class ArraysTest {
} }
} }
test fun dropWhile() { @test fun dropWhile() {
expect(listOf(), { intArrayOf().dropWhile { it < 3 } }) expect(listOf(), { intArrayOf().dropWhile { it < 3 } })
expect(listOf(), { intArrayOf(1).dropWhile { it < 3 } }) expect(listOf(), { intArrayOf(1).dropWhile { it < 3 } })
expect(listOf(3, 1), { intArrayOf(2, 3, 1).dropWhile { it < 3 } }) expect(listOf(3, 1), { intArrayOf(2, 3, 1).dropWhile { it < 3 } })
@@ -618,7 +618,7 @@ class ArraysTest {
expect(listOf("b", "a"), { arrayOf("a", "b", "a").dropWhile { it < "b" } }) expect(listOf("b", "a"), { arrayOf("a", "b", "a").dropWhile { it < "b" } })
} }
test fun dropLastWhile() { @test fun dropLastWhile() {
expect(listOf(), { intArrayOf().dropLastWhile { it < 3 } }) expect(listOf(), { intArrayOf().dropLastWhile { it < 3 } })
expect(listOf(), { intArrayOf(1).dropLastWhile { it < 3 } }) expect(listOf(), { intArrayOf(1).dropLastWhile { it < 3 } })
expect(listOf(2, 3), { intArrayOf(2, 3, 1).dropLastWhile { it < 3 } }) expect(listOf(2, 3), { intArrayOf(2, 3, 1).dropLastWhile { it < 3 } })
@@ -632,7 +632,7 @@ class ArraysTest {
expect(listOf("a", "b"), { arrayOf("a", "b", "a").dropLastWhile { it < "b" } }) expect(listOf("a", "b"), { arrayOf("a", "b", "a").dropLastWhile { it < "b" } })
} }
test fun take() { @test fun take() {
expect(listOf(), { intArrayOf().take(1) }) expect(listOf(), { intArrayOf().take(1) })
expect(listOf(), { intArrayOf(1).take(0) }) expect(listOf(), { intArrayOf(1).take(0) })
expect(listOf(1), { intArrayOf(1).take(1) }) expect(listOf(1), { intArrayOf(1).take(1) })
@@ -650,7 +650,7 @@ class ArraysTest {
} }
} }
test fun takeLast() { @test fun takeLast() {
expect(listOf(), { intArrayOf().takeLast(1) }) expect(listOf(), { intArrayOf().takeLast(1) })
expect(listOf(), { intArrayOf(1).takeLast(0) }) expect(listOf(), { intArrayOf(1).takeLast(0) })
expect(listOf(1), { intArrayOf(1).takeLast(1) }) expect(listOf(1), { intArrayOf(1).takeLast(1) })
@@ -668,7 +668,7 @@ class ArraysTest {
} }
} }
test fun takeWhile() { @test fun takeWhile() {
expect(listOf(), { intArrayOf().takeWhile { it < 3 } }) expect(listOf(), { intArrayOf().takeWhile { it < 3 } })
expect(listOf(1), { intArrayOf(1).takeWhile { it < 3 } }) expect(listOf(1), { intArrayOf(1).takeWhile { it < 3 } })
expect(listOf(2), { intArrayOf(2, 3, 1).takeWhile { it < 3 } }) expect(listOf(2), { intArrayOf(2, 3, 1).takeWhile { it < 3 } })
@@ -682,7 +682,7 @@ class ArraysTest {
expect(listOf("a"), { arrayOf("a", "c", "b").takeWhile { it < "c" } }) expect(listOf("a"), { arrayOf("a", "c", "b").takeWhile { it < "c" } })
} }
test fun takeLastWhile() { @test fun takeLastWhile() {
expect(listOf(), { intArrayOf().takeLastWhile { it < 3 } }) expect(listOf(), { intArrayOf().takeLastWhile { it < 3 } })
expect(listOf(1), { intArrayOf(1).takeLastWhile { it < 3 } }) expect(listOf(1), { intArrayOf(1).takeLastWhile { it < 3 } })
expect(listOf(1), { intArrayOf(2, 3, 1).takeLastWhile { it < 3 } }) expect(listOf(1), { intArrayOf(2, 3, 1).takeLastWhile { it < 3 } })
@@ -696,7 +696,7 @@ class ArraysTest {
expect(listOf("b"), { arrayOf("a", "c", "b").takeLastWhile { it < "c" } }) expect(listOf("b"), { arrayOf("a", "c", "b").takeLastWhile { it < "c" } })
} }
test fun filter() { @test fun filter() {
expect(listOf(), { intArrayOf().filter { it > 2 } }) expect(listOf(), { intArrayOf().filter { it > 2 } })
expect(listOf(), { intArrayOf(1).filter { it > 2 } }) expect(listOf(), { intArrayOf(1).filter { it > 2 } })
expect(listOf(3), { intArrayOf(2, 3).filter { it > 2 } }) expect(listOf(3), { intArrayOf(2, 3).filter { it > 2 } })
@@ -710,7 +710,7 @@ class ArraysTest {
expect(listOf("b"), { arrayOf("a", "b").filter { it > "a" } }) expect(listOf("b"), { arrayOf("a", "b").filter { it > "a" } })
} }
test fun filterNot() { @test fun filterNot() {
expect(listOf(), { intArrayOf().filterNot { it > 2 } }) expect(listOf(), { intArrayOf().filterNot { it > 2 } })
expect(listOf(1), { intArrayOf(1).filterNot { it > 2 } }) expect(listOf(1), { intArrayOf(1).filterNot { it > 2 } })
expect(listOf(2), { intArrayOf(2, 3).filterNot { it > 2 } }) expect(listOf(2), { intArrayOf(2, 3).filterNot { it > 2 } })
@@ -724,11 +724,11 @@ class ArraysTest {
expect(listOf("a"), { arrayOf("a", "b").filterNot { it > "a" } }) expect(listOf("a"), { arrayOf("a", "b").filterNot { it > "a" } })
} }
test fun filterNotNull() { @test fun filterNotNull() {
expect(listOf("a"), { arrayOf("a", null).filterNotNull() }) expect(listOf("a"), { arrayOf("a", null).filterNotNull() })
} }
test fun asListPrimitives() { @test fun asListPrimitives() {
// Array of primitives // Array of primitives
val arr = intArrayOf(1, 2, 3, 4, 2, 5) val arr = intArrayOf(1, 2, 3, 4, 2, 5)
val list = arr.asList() val list = arr.asList()
@@ -760,7 +760,7 @@ class ArraysTest {
assertEquals(IntArray(0).asList(), emptyList<Int>()) assertEquals(IntArray(0).asList(), emptyList<Int>())
} }
test fun asListObjects() { @test fun asListObjects() {
val arr = arrayOf("a", "b", "c", "d", "b", "e") val arr = arrayOf("a", "b", "c", "d", "b", "e")
val list = arr.asList() val list = arr.asList()
@@ -793,7 +793,7 @@ class ArraysTest {
assertEquals(Array(0, { "" }).asList(), emptyList<String>()) assertEquals(Array(0, { "" }).asList(), emptyList<String>())
} }
test fun sort() { @test fun sort() {
val intArr = intArrayOf(5, 2, 1, 9, 80, Int.MIN_VALUE, Int.MAX_VALUE) val intArr = intArrayOf(5, 2, 1, 9, 80, Int.MIN_VALUE, Int.MAX_VALUE)
intArr.sort() intArr.sort()
assertArrayNotSameButEquals(intArrayOf(Int.MIN_VALUE, 1, 2, 5, 9, 80, Int.MAX_VALUE), intArr) assertArrayNotSameButEquals(intArrayOf(Int.MIN_VALUE, 1, 2, 5, 9, 80, Int.MAX_VALUE), intArr)
@@ -811,7 +811,7 @@ class ArraysTest {
assertArrayNotSameButEquals(arrayOf("80", "9", "Foo", "all"), strArr) assertArrayNotSameButEquals(arrayOf("80", "9", "Foo", "all"), strArr)
} }
test fun sorted() { @test fun sorted() {
assertTrue(arrayOf<Long>().sorted().none()) assertTrue(arrayOf<Long>().sorted().none())
assertEquals(listOf(1), arrayOf(1).sorted()) assertEquals(listOf(1), arrayOf(1).sorted())
@@ -849,14 +849,14 @@ class ArraysTest {
} }
} }
test fun sortedBy() { @test fun sortedBy() {
val values = arrayOf("ac", "aD", "aba") val values = arrayOf("ac", "aD", "aba")
val indices = values.indices.toList().toIntArray() val indices = values.indices.toList().toIntArray()
assertEquals(listOf(1, 2, 0), indices.sortedBy { values[it] }) assertEquals(listOf(1, 2, 0), indices.sortedBy { values[it] })
} }
test fun sortedNullableBy() { @test fun sortedNullableBy() {
fun String.nullIfEmpty() = if (isEmpty()) null else this fun String.nullIfEmpty() = if (isEmpty()) null else this
arrayOf(null, "").let { arrayOf(null, "").let {
expect(listOf(null, "")) { it.sortedWith(nullsFirst(compareBy { it })) } expect(listOf(null, "")) { it.sortedWith(nullsFirst(compareBy { it })) }
@@ -865,7 +865,7 @@ class ArraysTest {
} }
} }
test fun sortedWith() { @test fun sortedWith() {
val comparator = compareBy { it: Int -> it % 3 }.thenByDescending { it } val comparator = compareBy { it: Int -> it % 3 }.thenByDescending { it }
fun arrayData<A, T>(array: A, comparator: Comparator<T>) = ArraySortedChecker<A, T>(array, comparator) fun arrayData<A, T>(array: A, comparator: Comparator<T>) = ArraySortedChecker<A, T>(array, comparator)
@@ -20,7 +20,7 @@ class CollectionJVMTest {
private data class IdentityData(public val value: Int) private data class IdentityData(public val value: Int)
test fun removeAllWithDifferentEquality() { @test fun removeAllWithDifferentEquality() {
val data = listOf(IdentityData(1), IdentityData(1)) val data = listOf(IdentityData(1), IdentityData(1))
val list = data.toArrayList() val list = data.toArrayList()
list -= identitySetOf(data[0]) as Iterable<IdentityData> list -= identitySetOf(data[0]) as Iterable<IdentityData>
@@ -35,7 +35,7 @@ class CollectionJVMTest {
assertTrue(set3.isEmpty(), "Array doesn't have contains, equality contains is used instead") assertTrue(set3.isEmpty(), "Array doesn't have contains, equality contains is used instead")
} }
test fun flatMap() { @test fun flatMap() {
val data = listOf("", "foo", "bar", "x", "") val data = listOf("", "foo", "bar", "x", "")
val characters = data.flatMap { it.toCharList() } val characters = data.flatMap { it.toCharList() }
println("Got list of characters ${characters}") println("Got list of characters ${characters}")
@@ -45,7 +45,7 @@ class CollectionJVMTest {
} }
test fun filterIntoLinkedList() { @test fun filterIntoLinkedList() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val foo = data.filterTo(linkedListOf<String>()) { it.startsWith("f") } val foo = data.filterTo(linkedListOf<String>()) { it.startsWith("f") }
@@ -60,7 +60,7 @@ class CollectionJVMTest {
} }
} }
test fun filterNotIntoLinkedListOf() { @test fun filterNotIntoLinkedListOf() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val foo = data.filterNotTo(linkedListOf<String>()) { it.startsWith("f") } val foo = data.filterNotTo(linkedListOf<String>()) { it.startsWith("f") }
@@ -75,7 +75,7 @@ class CollectionJVMTest {
} }
} }
test fun filterNotNullIntoLinkedListOf() { @test fun filterNotNullIntoLinkedListOf() {
val data = listOf(null, "foo", null, "bar") val data = listOf(null, "foo", null, "bar")
val foo = data.filterNotNullTo(linkedListOf<String>()) val foo = data.filterNotNullTo(linkedListOf<String>())
@@ -87,7 +87,7 @@ class CollectionJVMTest {
} }
} }
test fun filterIntoSortedSet() { @test fun filterIntoSortedSet() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val sorted = data.filterTo(sortedSetOf<String>()) { it.length() == 3 } val sorted = data.filterTo(sortedSetOf<String>()) { it.length() == 3 }
assertEquals(2, sorted.size()) assertEquals(2, sorted.size())
@@ -97,26 +97,26 @@ class CollectionJVMTest {
} }
} }
test fun first() { @test fun first() {
assertEquals(19, TreeSet(listOf(90, 47, 19)).first()) assertEquals(19, TreeSet(listOf(90, 47, 19)).first())
} }
test fun last() { @test fun last() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals("bar", data.last()) assertEquals("bar", data.last())
assertEquals(25, listOf(15, 19, 20, 25).last()) assertEquals(25, listOf(15, 19, 20, 25).last())
assertEquals('a', linkedListOf('a').last()) assertEquals('a', linkedListOf('a').last())
} }
test fun lastException() { @test fun lastException() {
fails { linkedListOf<String>().last() } fails { linkedListOf<String>().last() }
} }
test fun contains() { @test fun contains() {
assertTrue(linkedListOf(15, 19, 20).contains(15)) assertTrue(linkedListOf(15, 19, 20).contains(15))
} }
test fun toArray() { @test fun toArray() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val arr = data.toTypedArray() val arr = data.toTypedArray()
println("Got array ${arr}") println("Got array ${arr}")
@@ -128,11 +128,11 @@ class CollectionJVMTest {
} }
} }
test fun takeReturnsFirstNElements() { @test fun takeReturnsFirstNElements() {
expect(setOf(1, 2)) { sortedSetOf(1, 2, 3, 4, 5).take(2).toSet() } expect(setOf(1, 2)) { sortedSetOf(1, 2, 3, 4, 5).take(2).toSet() }
} }
test fun filterIsInstanceList() { @test fun filterIsInstanceList() {
val values: List<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde") val values: List<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde")
val intValues: List<Int> = values.filterIsInstance<Int>() val intValues: List<Int> = values.filterIsInstance<Int>()
@@ -151,7 +151,7 @@ class CollectionJVMTest {
assertEquals(0, charValues.size()) assertEquals(0, charValues.size())
} }
test fun filterIsInstanceArray() { @test fun filterIsInstanceArray() {
val src: Array<Any> = arrayOf(1, 2, 3.toDouble(), "abc", "cde") val src: Array<Any> = arrayOf(1, 2, 3.toDouble(), "abc", "cde")
val intValues: List<Int> = src.filterIsInstance<Int>() val intValues: List<Int> = src.filterIsInstance<Int>()
@@ -170,11 +170,11 @@ class CollectionJVMTest {
assertEquals(0, charValues.size()) assertEquals(0, charValues.size())
} }
test fun emptyListIsSerializable() = testSingletonSerialization(emptyList<Any>()) @test fun emptyListIsSerializable() = testSingletonSerialization(emptyList<Any>())
test fun emptySetIsSerializable() = testSingletonSerialization(emptySet<Any>()) @test fun emptySetIsSerializable() = testSingletonSerialization(emptySet<Any>())
test fun emptyMapIsSerializable() = testSingletonSerialization(emptyMap<Any, Any>()) @test fun emptyMapIsSerializable() = testSingletonSerialization(emptyMap<Any, Any>())
private fun testSingletonSerialization(value: Any) { private fun testSingletonSerialization(value: Any) {
val result = serializeAndDeserialize(value) val result = serializeAndDeserialize(value)
@@ -7,14 +7,14 @@ import test.collections.behaviors.*
class CollectionTest { class CollectionTest {
test fun joinTo() { @test fun joinTo() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val buffer = StringBuilder() val buffer = StringBuilder()
data.joinTo(buffer, "-", "{", "}") data.joinTo(buffer, "-", "{", "}")
assertEquals("{foo-bar}", buffer.toString()) assertEquals("{foo-bar}", buffer.toString())
} }
test fun join() { @test fun join() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val text = data.join("-", "<", ">") val text = data.join("-", "<", ">")
assertEquals("<foo-bar>", text) assertEquals("<foo-bar>", text)
@@ -24,7 +24,7 @@ class CollectionTest {
assertEquals("a, b, c, *", text2) assertEquals("a, b, c, *", text2)
} }
test fun filterNotNull() { @test fun filterNotNull() {
val data = listOf(null, "foo", null, "bar") val data = listOf(null, "foo", null, "bar")
val foo = data.filterNotNull() val foo = data.filterNotNull()
@@ -36,7 +36,7 @@ class CollectionTest {
} }
} }
test fun mapNotNull() { @test fun mapNotNull() {
val data = listOf(null, "foo", null, "bar") val data = listOf(null, "foo", null, "bar")
val foo = data.mapNotNull { it.length() } val foo = data.mapNotNull { it.length() }
assertEquals(2, foo.size()) assertEquals(2, foo.size())
@@ -47,7 +47,7 @@ class CollectionTest {
} }
} }
test fun listOfNotNull() { @test fun listOfNotNull() {
val l1: List<Int> = listOfNotNull(null) val l1: List<Int> = listOfNotNull(null)
assertTrue(l1.isEmpty()) assertTrue(l1.isEmpty())
@@ -59,7 +59,7 @@ class CollectionTest {
assertEquals(listOf("value1", "value2"), l3) assertEquals(listOf("value1", "value2"), l3)
} }
test fun filterIntoSet() { @test fun filterIntoSet() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val foo = data.filterTo(hashSetOf<String>()) { it.startsWith("f") } val foo = data.filterTo(hashSetOf<String>()) { it.startsWith("f") }
@@ -74,7 +74,7 @@ class CollectionTest {
} }
} }
test fun fold() { @test fun fold() {
// lets calculate the sum of some numbers // lets calculate the sum of some numbers
expect(10) { expect(10) {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
@@ -93,7 +93,7 @@ class CollectionTest {
} }
} }
test fun foldWithDifferentTypes() { @test fun foldWithDifferentTypes() {
expect(7) { expect(7) {
val numbers = listOf("a", "ab", "abc") val numbers = listOf("a", "ab", "abc")
numbers.fold(1) { a, b -> a + b.length() } numbers.fold(1) { a, b -> a + b.length() }
@@ -105,49 +105,49 @@ class CollectionTest {
} }
} }
test fun foldWithNonCommutativeOperation() { @test fun foldWithNonCommutativeOperation() {
expect(1) { expect(1) {
val numbers = listOf(1, 2, 3) val numbers = listOf(1, 2, 3)
numbers.fold(7) { a, b -> a - b } numbers.fold(7) { a, b -> a - b }
} }
} }
test fun foldRight() { @test fun foldRight() {
expect("1234") { expect("1234") {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
numbers.map { it.toString() }.foldRight("") { a, b -> a + b } numbers.map { it.toString() }.foldRight("") { a, b -> a + b }
} }
} }
test fun foldRightWithDifferentTypes() { @test fun foldRightWithDifferentTypes() {
expect("1234") { expect("1234") {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
numbers.foldRight("") { a, b -> "" + a + b } numbers.foldRight("") { a, b -> "" + a + b }
} }
} }
test fun foldRightWithNonCommutativeOperation() { @test fun foldRightWithNonCommutativeOperation() {
expect(-5) { expect(-5) {
val numbers = listOf(1, 2, 3) val numbers = listOf(1, 2, 3)
numbers.foldRight(7) { a, b -> a - b } numbers.foldRight(7) { a, b -> a - b }
} }
} }
test @test
fun merge() { fun merge() {
expect(listOf("ab", "bc", "cd")) { expect(listOf("ab", "bc", "cd")) {
listOf("a", "b", "c").merge(listOf("b", "c", "d")) { a, b -> a + b } listOf("a", "b", "c").merge(listOf("b", "c", "d")) { a, b -> a + b }
} }
} }
test @test
fun zip() { fun zip() {
expect(listOf("a" to "b", "b" to "c", "c" to "d")) { expect(listOf("a" to "b", "b" to "c", "c" to "d")) {
listOf("a", "b", "c").zip(listOf("b", "c", "d")) listOf("a", "b", "c").zip(listOf("b", "c", "d"))
} }
} }
test fun partition() { @test fun partition() {
val data = listOf("foo", "bar", "something", "xyz") val data = listOf("foo", "bar", "something", "xyz")
val pair = data.partition { it.length() == 3 } val pair = data.partition { it.length() == 3 }
@@ -155,7 +155,7 @@ class CollectionTest {
assertEquals(listOf("something"), pair.second, "pair.second") assertEquals(listOf("something"), pair.second, "pair.second")
} }
test fun reduce() { @test fun reduce() {
expect("1234") { expect("1234") {
val list = listOf("1", "2", "3", "4") val list = listOf("1", "2", "3", "4")
list.reduce { a, b -> a + b } list.reduce { a, b -> a + b }
@@ -168,7 +168,7 @@ class CollectionTest {
} }
} }
test fun reduceRight() { @test fun reduceRight() {
expect("1234") { expect("1234") {
val list = listOf("1", "2", "3", "4") val list = listOf("1", "2", "3", "4")
list.reduceRight { a, b -> a + b } list.reduceRight { a, b -> a + b }
@@ -181,7 +181,7 @@ class CollectionTest {
} }
} }
test fun groupBy() { @test fun groupBy() {
val words = listOf("a", "abc", "ab", "def", "abcd") val words = listOf("a", "abc", "ab", "def", "abcd")
val byLength = words.groupBy { it.length() } val byLength = words.groupBy { it.length() }
assertEquals(4, byLength.size()) assertEquals(4, byLength.size())
@@ -197,14 +197,14 @@ class CollectionTest {
assertEquals(2, l3.size()) assertEquals(2, l3.size())
} }
test fun plusRanges() { @test fun plusRanges() {
val range1 = 1..3 val range1 = 1..3
val range2 = 4..7 val range2 = 4..7
val combined = range1 + range2 val combined = range1 + range2
assertEquals((1..7).toList(), combined) assertEquals((1..7).toList(), combined)
} }
test fun mapRanges() { @test fun mapRanges() {
val range = 1..3 map { it * 2 } val range = 1..3 map { it * 2 }
assertEquals(listOf(2, 4, 6), range) assertEquals(listOf(2, 4, 6), range)
} }
@@ -216,18 +216,18 @@ class CollectionTest {
assertEquals(listOf("foo", "bar", "cheese", "wine"), list2) assertEquals(listOf("foo", "bar", "cheese", "wine"), list2)
} }
test fun plusElement() = testPlus { it + "cheese" + "wine" } @test fun plusElement() = testPlus { it + "cheese" + "wine" }
test fun plusCollection() = testPlus { it + listOf("cheese", "wine") } @test fun plusCollection() = testPlus { it + listOf("cheese", "wine") }
test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") } @test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") }
test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") } @test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") }
test fun plusCollectionBug() { @test fun plusCollectionBug() {
val list = listOf("foo", "bar") + listOf("cheese", "wine") val list = listOf("foo", "bar") + listOf("cheese", "wine")
assertEquals(listOf("foo", "bar", "cheese", "wine"), list) assertEquals(listOf("foo", "bar", "cheese", "wine"), list)
} }
test fun plusAssign() { @test fun plusAssign() {
// lets use a mutable variable of readonly list // lets use a mutable variable of readonly list
var l: List<String> = listOf("cheese") var l: List<String> = listOf("cheese")
val lOriginal = l val lOriginal = l
@@ -254,12 +254,12 @@ class CollectionTest {
assertEquals(expected_, b.toList()) assertEquals(expected_, b.toList())
} }
test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" } @test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" }
test fun minusCollection() = testMinus { it - listOf("bar", "zoo") } @test fun minusCollection() = testMinus { it - listOf("bar", "zoo") }
test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") } @test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") }
test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") } @test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") }
test fun minusIsEager() { @test fun minusIsEager() {
val source = listOf("foo", "bar") val source = listOf("foo", "bar")
val list = arrayListOf<String>() val list = arrayListOf<String>()
val result = source - list val result = source - list
@@ -270,7 +270,7 @@ class CollectionTest {
assertEquals(source, result) assertEquals(source, result)
} }
test fun minusAssign() { @test fun minusAssign() {
// lets use a mutable variable of readonly list // lets use a mutable variable of readonly list
val data: List<String> = listOf("cheese", "foo", "beer", "cheese", "wine") val data: List<String> = listOf("cheese", "foo", "beer", "cheese", "wine")
var l = data var l = data
@@ -293,7 +293,7 @@ class CollectionTest {
test fun requireNoNulls() { @test fun requireNoNulls() {
val data = arrayListOf<String?>("foo", "bar") val data = arrayListOf<String?>("foo", "bar")
val notNull = data.requireNoNulls() val notNull = data.requireNoNulls()
assertEquals(listOf("foo", "bar"), notNull) assertEquals(listOf("foo", "bar"), notNull)
@@ -308,37 +308,37 @@ class CollectionTest {
} }
} }
test fun reverse() { @test fun reverse() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val rev = data.reversed() val rev = data.reversed()
assertEquals(listOf("bar", "foo"), rev) assertEquals(listOf("bar", "foo"), rev)
} }
test fun reverseFunctionShouldReturnReversedCopyForList() { @test fun reverseFunctionShouldReturnReversedCopyForList() {
val list: List<Int> = listOf(2, 3, 1) val list: List<Int> = listOf(2, 3, 1)
expect(listOf(1, 3, 2)) { list.reversed() } expect(listOf(1, 3, 2)) { list.reversed() }
expect(listOf(2, 3, 1)) { list } expect(listOf(2, 3, 1)) { list }
} }
test fun reverseFunctionShouldReturnReversedCopyForIterable() { @test fun reverseFunctionShouldReturnReversedCopyForIterable() {
val iterable: Iterable<Int> = listOf(2, 3, 1) val iterable: Iterable<Int> = listOf(2, 3, 1)
expect(listOf(1, 3, 2)) { iterable.reversed() } expect(listOf(1, 3, 2)) { iterable.reversed() }
expect(listOf(2, 3, 1)) { iterable } expect(listOf(2, 3, 1)) { iterable }
} }
test fun drop() { @test fun drop() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(listOf("bar", "abc"), coll.drop(1)) assertEquals(listOf("bar", "abc"), coll.drop(1))
assertEquals(listOf("abc"), coll.drop(2)) assertEquals(listOf("abc"), coll.drop(2))
} }
test fun dropWhile() { @test fun dropWhile() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(listOf("bar", "abc"), coll.dropWhile { it.startsWith("f") }) assertEquals(listOf("bar", "abc"), coll.dropWhile { it.startsWith("f") })
} }
test fun dropLast() { @test fun dropLast() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(coll, coll.dropLast(0)) assertEquals(coll, coll.dropLast(0))
assertEquals(emptyList<String>(), coll.dropLast(coll.size())) assertEquals(emptyList<String>(), coll.dropLast(coll.size()))
@@ -349,7 +349,7 @@ class CollectionTest {
fails { coll.dropLast(-1) } fails { coll.dropLast(-1) }
} }
test fun dropLastWhile() { @test fun dropLastWhile() {
val coll = listOf("Foo", "bare", "abc" ) val coll = listOf("Foo", "bare", "abc" )
assertEquals(coll, coll.dropLastWhile { false }) assertEquals(coll, coll.dropLastWhile { false })
assertEquals(listOf<String>(), coll.dropLastWhile { true }) assertEquals(listOf<String>(), coll.dropLastWhile { true })
@@ -357,7 +357,7 @@ class CollectionTest {
assertEquals(listOf("Foo"), coll.dropLastWhile { it.all { it in 'a'..'z' } }) assertEquals(listOf("Foo"), coll.dropLastWhile { it.all { it in 'a'..'z' } })
} }
test fun take() { @test fun take() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.take(0)) assertEquals(emptyList<String>(), coll.take(0))
assertEquals(listOf("foo"), coll.take(1)) assertEquals(listOf("foo"), coll.take(1))
@@ -368,7 +368,7 @@ class CollectionTest {
fails { coll.take(-1) } fails { coll.take(-1) }
} }
test fun takeWhile() { @test fun takeWhile() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.takeWhile { false }) assertEquals(emptyList<String>(), coll.takeWhile { false })
assertEquals(coll, coll.takeWhile { true }) assertEquals(coll, coll.takeWhile { true })
@@ -376,7 +376,7 @@ class CollectionTest {
assertEquals(listOf("foo", "bar", "abc"), coll.takeWhile { it.length() == 3 }) assertEquals(listOf("foo", "bar", "abc"), coll.takeWhile { it.length() == 3 })
} }
test fun takeLast() { @test fun takeLast() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.takeLast(0)) assertEquals(emptyList<String>(), coll.takeLast(0))
@@ -388,7 +388,7 @@ class CollectionTest {
fails { coll.takeLast(-1) } fails { coll.takeLast(-1) }
} }
test fun takeLastWhile() { @test fun takeLastWhile() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.takeLastWhile { false }) assertEquals(emptyList<String>(), coll.takeLastWhile { false })
assertEquals(coll, coll.takeLastWhile { true }) assertEquals(coll, coll.takeLastWhile { true })
@@ -396,7 +396,7 @@ class CollectionTest {
assertEquals(listOf("bar", "abc"), coll.takeLastWhile { it[0] < 'c' }) assertEquals(listOf("bar", "abc"), coll.takeLastWhile { it[0] < 'c' })
} }
test fun copyToArray() { @test fun copyToArray() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val arr = data.toTypedArray() val arr = data.toTypedArray()
println("Got array ${arr}") println("Got array ${arr}")
@@ -408,14 +408,14 @@ class CollectionTest {
} }
} }
test fun count() { @test fun count() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals(2, data.count()) assertEquals(2, data.count())
assertEquals(3, hashSetOf(12, 14, 15).count()) assertEquals(3, hashSetOf(12, 14, 15).count())
assertEquals(0, ArrayList<Double>().count()) assertEquals(0, ArrayList<Double>().count())
} }
test fun first() { @test fun first() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals("foo", data.first()) assertEquals("foo", data.first())
assertEquals(15, listOf(15, 19, 20, 25).first()) assertEquals(15, listOf(15, 19, 20, 25).first())
@@ -423,7 +423,7 @@ class CollectionTest {
fails { arrayListOf<Int>().first() } fails { arrayListOf<Int>().first() }
} }
test fun last() { @test fun last() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals("bar", data.last()) assertEquals("bar", data.last())
assertEquals(25, listOf(15, 19, 20, 25).last()) assertEquals(25, listOf(15, 19, 20, 25).last())
@@ -431,7 +431,7 @@ class CollectionTest {
fails { arrayListOf<Int>().last() } fails { arrayListOf<Int>().last() }
} }
test fun subscript() { @test fun subscript() {
val list = arrayListOf("foo", "bar") val list = arrayListOf("foo", "bar")
assertEquals("foo", list[0]) assertEquals("foo", list[0])
assertEquals("bar", list[1]) assertEquals("bar", list[1])
@@ -454,7 +454,7 @@ class CollectionTest {
assertEquals(listOf("new", "thing", "works"), list) assertEquals(listOf("new", "thing", "works"), list)
} }
test fun indices() { @test fun indices() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val indices = data.indices val indices = data.indices
assertEquals(0, indices.start) assertEquals(0, indices.start)
@@ -462,14 +462,14 @@ class CollectionTest {
assertEquals(0..data.size() - 1, indices) assertEquals(0..data.size() - 1, indices)
} }
test fun contains() { @test fun contains() {
assertFalse(hashSetOf<Int>().contains(12)) assertFalse(hashSetOf<Int>().contains(12))
assertTrue(listOf(15, 19, 20).contains(15)) assertTrue(listOf(15, 19, 20).contains(15))
assertTrue(IterableWrapper(hashSetOf(45, 14, 13)).contains(14)) assertTrue(IterableWrapper(hashSetOf(45, 14, 13)).contains(14))
} }
test fun min() { @test fun min() {
expect(null, { listOf<Int>().min() }) expect(null, { listOf<Int>().min() })
expect(1, { listOf(1).min() }) expect(1, { listOf(1).min() })
expect(2, { listOf(2, 3).min() }) expect(2, { listOf(2, 3).min() })
@@ -480,7 +480,7 @@ class CollectionTest {
expect(2, { listOf(2, 3).asSequence().min() }) expect(2, { listOf(2, 3).asSequence().min() })
} }
test fun max() { @test fun max() {
expect(null, { listOf<Int>().max() }) expect(null, { listOf<Int>().max() })
expect(1, { listOf(1).max() }) expect(1, { listOf(1).max() })
expect(3, { listOf(2, 3).max() }) expect(3, { listOf(2, 3).max() })
@@ -491,7 +491,7 @@ class CollectionTest {
expect(3, { listOf(2, 3).asSequence().max() }) expect(3, { listOf(2, 3).asSequence().max() })
} }
test fun minBy() { @test fun minBy() {
expect(null, { listOf<Int>().minBy { it } }) expect(null, { listOf<Int>().minBy { it } })
expect(1, { listOf(1).minBy { it } }) expect(1, { listOf(1).minBy { it } })
expect(3, { listOf(2, 3).minBy { -it } }) expect(3, { listOf(2, 3).minBy { -it } })
@@ -501,7 +501,7 @@ class CollectionTest {
expect(3, { listOf(2, 3).asSequence().minBy { -it } }) expect(3, { listOf(2, 3).asSequence().minBy { -it } })
} }
test fun maxBy() { @test fun maxBy() {
expect(null, { listOf<Int>().maxBy { it } }) expect(null, { listOf<Int>().maxBy { it } })
expect(1, { listOf(1).maxBy { it } }) expect(1, { listOf(1).maxBy { it } })
expect(2, { listOf(2, 3).maxBy { -it } }) expect(2, { listOf(2, 3).maxBy { -it } })
@@ -511,7 +511,7 @@ class CollectionTest {
expect(2, { listOf(2, 3).asSequence().maxBy { -it } }) expect(2, { listOf(2, 3).asSequence().maxBy { -it } })
} }
test fun minByEvaluateOnce() { @test fun minByEvaluateOnce() {
var c = 0 var c = 0
expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } }) expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
@@ -520,7 +520,7 @@ class CollectionTest {
assertEquals(5, c) assertEquals(5, c)
} }
test fun maxByEvaluateOnce() { @test fun maxByEvaluateOnce() {
var c = 0 var c = 0
expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } }) expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
@@ -529,7 +529,7 @@ class CollectionTest {
assertEquals(5, c) assertEquals(5, c)
} }
test fun sum() { @test fun sum() {
expect(0) { arrayListOf<Int>().sum() } expect(0) { arrayListOf<Int>().sum() }
expect(14) { listOf(2, 3, 9).sum() } expect(14) { listOf(2, 3, 9).sum() }
expect(3.0) { listOf(1.0, 2.0).sum() } expect(3.0) { listOf(1.0, 2.0).sum() }
@@ -538,7 +538,7 @@ class CollectionTest {
expect(3.0.toFloat()) { sequenceOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() } expect(3.0.toFloat()) { sequenceOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
} }
test fun average() { @test fun average() {
expect(0.0) { arrayListOf<Int>().average() } expect(0.0) { arrayListOf<Int>().average() }
expect(3.8) { listOf(1, 2, 5, 8, 3).average() } expect(3.8) { listOf(1, 2, 5, 8, 3).average() }
expect(2.1) { sequenceOf(1.6, 2.6, 3.6, 0.6).average() } expect(2.1) { sequenceOf(1.6, 2.6, 3.6, 0.6).average() }
@@ -548,7 +548,7 @@ class CollectionTest {
expect(n.toDouble()/2) { range.average() } expect(n.toDouble()/2) { range.average() }
} }
test fun takeReturnsFirstNElements() { @test fun takeReturnsFirstNElements() {
expect(listOf(1, 2, 3, 4, 5)) { (1..10) take 5 } expect(listOf(1, 2, 3, 4, 5)) { (1..10) take 5 }
expect(listOf(1, 2, 3, 4, 5)) { (1..10).toList().take(5) } expect(listOf(1, 2, 3, 4, 5)) { (1..10).toList().take(5) }
expect(listOf(1, 2)) { (1..10) take 2 } expect(listOf(1, 2)) { (1..10) take 2 }
@@ -559,18 +559,18 @@ class CollectionTest {
expect(listOf(1)) { listOf(1) take 10 } expect(listOf(1)) { listOf(1) take 10 }
} }
test fun sorted() { @test fun sorted() {
assertEquals(listOf(1, 3, 7), listOf(3, 7, 1).sorted()) assertEquals(listOf(1, 3, 7), listOf(3, 7, 1).sorted())
assertEquals(listOf(7, 3, 1), listOf(3, 7, 1).sortedDescending()) assertEquals(listOf(7, 3, 1), listOf(3, 7, 1).sortedDescending())
} }
test fun sortedBy() { @test fun sortedBy() {
assertEquals(listOf("two" to 2, "three" to 3), listOf("three" to 3, "two" to 2).sortedBy { it.second }) assertEquals(listOf("two" to 2, "three" to 3), listOf("three" to 3, "two" to 2).sortedBy { it.second })
assertEquals(listOf("three" to 3, "two" to 2), listOf("three" to 3, "two" to 2).sortedBy { it.first }) assertEquals(listOf("three" to 3, "two" to 2), listOf("three" to 3, "two" to 2).sortedBy { it.first })
assertEquals(listOf("three", "two"), listOf("two", "three").sortedByDescending { it.length() }) assertEquals(listOf("three", "two"), listOf("two", "three").sortedByDescending { it.length() })
} }
test fun sortedNullableBy() { @test fun sortedNullableBy() {
fun String.nullIfEmpty() = if (isEmpty()) null else this fun String.nullIfEmpty() = if (isEmpty()) null else this
listOf(null, "", "a").let { listOf(null, "", "a").let {
expect(listOf(null, "", "a")) { it.sortedWith(nullsFirst(compareBy { it })) } expect(listOf(null, "", "a")) { it.sortedWith(nullsFirst(compareBy { it })) }
@@ -579,7 +579,7 @@ class CollectionTest {
} }
} }
test fun sortedByNullable() { @test fun sortedByNullable() {
fun String.nonEmptyLength() = if (isEmpty()) null else length() fun String.nonEmptyLength() = if (isEmpty()) null else length()
listOf("", "sort", "abc").let { listOf("", "sort", "abc").let {
assertEquals(listOf("", "abc", "sort"), it.sortedBy { it.nonEmptyLength() }) assertEquals(listOf("", "abc", "sort"), it.sortedBy { it.nonEmptyLength() })
@@ -588,7 +588,7 @@ class CollectionTest {
} }
} }
test fun sortedWith() { @test fun sortedWith() {
val comparator = compareBy<String> { it.toUpperCase().reversed() } val comparator = compareBy<String> { it.toUpperCase().reversed() }
val data = listOf("cat", "dad", "BAD") val data = listOf("cat", "dad", "BAD")
@@ -597,18 +597,18 @@ class CollectionTest {
expect(listOf("BAD", "dad", "cat")) { data.sortedWith(comparator.reversed().reversed()) } expect(listOf("BAD", "dad", "cat")) { data.sortedWith(comparator.reversed().reversed()) }
} }
test fun decomposeFirst() { @test fun decomposeFirst() {
val (first) = listOf(1, 2) val (first) = listOf(1, 2)
assertEquals(first, 1) assertEquals(first, 1)
} }
test fun decomposeSplit() { @test fun decomposeSplit() {
val (key, value) = "key = value".split("=").map { it.trim() } val (key, value) = "key = value".split("=").map { it.trim() }
assertEquals(key, "key") assertEquals(key, "key")
assertEquals(value, "value") assertEquals(value, "value")
} }
test fun decomposeList() { @test fun decomposeList() {
val (a, b, c, d, e) = listOf(1, 2, 3, 4, 5) val (a, b, c, d, e) = listOf(1, 2, 3, 4, 5)
assertEquals(a, 1) assertEquals(a, 1)
assertEquals(b, 2) assertEquals(b, 2)
@@ -617,7 +617,7 @@ class CollectionTest {
assertEquals(e, 5) assertEquals(e, 5)
} }
test fun decomposeArray() { @test fun decomposeArray() {
val (a, b, c, d, e) = arrayOf(1, 2, 3, 4, 5) val (a, b, c, d, e) = arrayOf(1, 2, 3, 4, 5)
assertEquals(a, 1) assertEquals(a, 1)
assertEquals(b, 2) assertEquals(b, 2)
@@ -626,7 +626,7 @@ class CollectionTest {
assertEquals(e, 5) assertEquals(e, 5)
} }
test fun decomposeIntArray() { @test fun decomposeIntArray() {
val (a, b, c, d, e) = intArrayOf(1, 2, 3, 4, 5) val (a, b, c, d, e) = intArrayOf(1, 2, 3, 4, 5)
assertEquals(a, 1) assertEquals(a, 1)
assertEquals(b, 2) assertEquals(b, 2)
@@ -635,39 +635,39 @@ class CollectionTest {
assertEquals(e, 5) assertEquals(e, 5)
} }
test fun unzipList() { @test fun unzipList() {
val list = listOf(1 to 'a', 2 to 'b', 3 to 'c') val list = listOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = list.unzip() val (ints, chars) = list.unzip()
assertEquals(listOf(1, 2, 3), ints) assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars) assertEquals(listOf('a', 'b', 'c'), chars)
} }
test fun unzipArray() { @test fun unzipArray() {
val array = arrayOf(1 to 'a', 2 to 'b', 3 to 'c') val array = arrayOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = array.unzip() val (ints, chars) = array.unzip()
assertEquals(listOf(1, 2, 3), ints) assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars) assertEquals(listOf('a', 'b', 'c'), chars)
} }
test fun specialLists() { @test fun specialLists() {
compare(arrayListOf<Int>(), listOf<Int>()) { listBehavior() } compare(arrayListOf<Int>(), listOf<Int>()) { listBehavior() }
compare(arrayListOf<Double>(), emptyList<Double>()) { listBehavior() } compare(arrayListOf<Double>(), emptyList<Double>()) { listBehavior() }
compare(arrayListOf("value"), listOf("value")) { listBehavior() } compare(arrayListOf("value"), listOf("value")) { listBehavior() }
} }
test fun specialSets() { @test fun specialSets() {
compare(linkedSetOf<Int>(), setOf<Int>()) { setBehavior() } compare(linkedSetOf<Int>(), setOf<Int>()) { setBehavior() }
compare(hashSetOf<Double>(), emptySet<Double>()) { setBehavior() } compare(hashSetOf<Double>(), emptySet<Double>()) { setBehavior() }
compare(listOf("value").toMutableSet(), setOf("value")) { setBehavior() } compare(listOf("value").toMutableSet(), setOf("value")) { setBehavior() }
} }
test fun specialMaps() { @test fun specialMaps() {
compare(hashMapOf<String, Int>(), mapOf<String, Int>()) { mapBehavior() } compare(hashMapOf<String, Int>(), mapOf<String, Int>()) { mapBehavior() }
compare(linkedMapOf<Int, String>(), emptyMap<Int, String>()) { mapBehavior() } compare(linkedMapOf<Int, String>(), emptyMap<Int, String>()) { mapBehavior() }
compare(linkedMapOf(2 to 3), mapOf(2 to 3)) { mapBehavior() } compare(linkedMapOf(2 to 3), mapOf(2 to 3)) { mapBehavior() }
} }
test fun toStringTest() { @test fun toStringTest() {
// we need toString() inside pattern because of KT-8666 // we need toString() inside pattern because of KT-8666
assertEquals("[1, a, null, ${Long.MAX_VALUE.toString()}]", listOf(1, "a", null, Long.MAX_VALUE).toString()) assertEquals("[1, a, null, ${Long.MAX_VALUE.toString()}]", listOf(1, "a", null, Long.MAX_VALUE).toString())
} }
@@ -22,33 +22,38 @@ class ListTest : OrderedIterableTests<List<String>>(listOf("foo", "bar"), listOf
class ArrayListTest : OrderedIterableTests<ArrayList<String>>(arrayListOf("foo", "bar"), arrayListOf<String>()) class ArrayListTest : OrderedIterableTests<ArrayList<String>>(arrayListOf("foo", "bar"), arrayListOf<String>())
abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : IterableTests<T>(data, empty) { abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : IterableTests<T>(data, empty) {
Test fun indexOf() { @Test
fun indexOf() {
expect(0) { data.indexOf("foo") } expect(0) { data.indexOf("foo") }
expect(-1) { empty.indexOf("foo") } expect(-1) { empty.indexOf("foo") }
expect(1) { data.indexOf("bar") } expect(1) { data.indexOf("bar") }
expect(-1) { data.indexOf("zap") } expect(-1) { data.indexOf("zap") }
} }
Test fun lastIndexOf() { @Test
fun lastIndexOf() {
expect(0) { data.lastIndexOf("foo") } expect(0) { data.lastIndexOf("foo") }
expect(-1) { empty.lastIndexOf("foo") } expect(-1) { empty.lastIndexOf("foo") }
expect(1) { data.lastIndexOf("bar") } expect(1) { data.lastIndexOf("bar") }
expect(-1) { data.lastIndexOf("zap") } expect(-1) { data.lastIndexOf("zap") }
} }
Test fun indexOfFirst() { @Test
fun indexOfFirst() {
expect(-1) { data.indexOfFirst { it.contains("p") } } expect(-1) { data.indexOfFirst { it.contains("p") } }
expect(0) { data.indexOfFirst { it.startsWith('f') } } expect(0) { data.indexOfFirst { it.startsWith('f') } }
expect(-1) { empty.indexOfFirst { it.startsWith('f') } } expect(-1) { empty.indexOfFirst { it.startsWith('f') } }
} }
Test fun indexOfLast() { @Test
fun indexOfLast() {
expect(-1) { data.indexOfLast { it.contains("p") } } expect(-1) { data.indexOfLast { it.contains("p") } }
expect(1) { data.indexOfLast { it.length() == 3 } } expect(1) { data.indexOfLast { it.length() == 3 } }
expect(-1) { empty.indexOfLast { it.startsWith('f') } } expect(-1) { empty.indexOfLast { it.startsWith('f') } }
} }
Test fun elementAt() { @Test
fun elementAt() {
expect("foo") { data.elementAt(0) } expect("foo") { data.elementAt(0) }
expect("bar") { data.elementAt(1) } expect("bar") { data.elementAt(1) }
fails { data.elementAt(2) } fails { data.elementAt(2) }
@@ -64,7 +69,8 @@ abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : I
} }
Test fun first() { @Test
fun first() {
expect("foo") { data.first() } expect("foo") { data.first() }
fails { fails {
data.first { it.startsWith("x") } data.first { it.startsWith("x") }
@@ -75,7 +81,8 @@ abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : I
expect("foo") { data.first { it.startsWith("f") } } expect("foo") { data.first { it.startsWith("f") } }
} }
Test fun firstOrNull() { @Test
fun firstOrNull() {
expect(null) { data.firstOrNull { it.startsWith("x") } } expect(null) { data.firstOrNull { it.startsWith("x") } }
expect(null) { empty.firstOrNull() } expect(null) { empty.firstOrNull() }
@@ -83,7 +90,8 @@ abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : I
assertEquals("foo", f) assertEquals("foo", f)
} }
Test fun last() { @Test
fun last() {
assertEquals("bar", data.last()) assertEquals("bar", data.last())
fails { fails {
data.last { it.startsWith("x") } data.last { it.startsWith("x") }
@@ -94,7 +102,8 @@ abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : I
expect("foo") { data.last { it.startsWith("f") } } expect("foo") { data.last { it.startsWith("f") } }
} }
Test fun lastOrNull() { @Test
fun lastOrNull() {
expect(null) { data.lastOrNull { it.startsWith("x") } } expect(null) { data.lastOrNull { it.startsWith("x") } }
expect(null) { empty.lastOrNull() } expect(null) { empty.lastOrNull() }
expect("foo") { data.lastOrNull { it.startsWith("f") } } expect("foo") { data.lastOrNull { it.startsWith("f") } }
@@ -102,7 +111,8 @@ abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : I
} }
abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) { abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
Test fun any() { @Test
fun any() {
expect(true) { data.any() } expect(true) { data.any() }
expect(false) { empty.any() } expect(false) { empty.any() }
expect(true) { data.any { it.startsWith("f") } } expect(true) { data.any { it.startsWith("f") } }
@@ -110,13 +120,15 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
expect(false) { empty.any { it.startsWith("x") } } expect(false) { empty.any { it.startsWith("x") } }
} }
Test fun all() { @Test
fun all() {
expect(true) { data.all { it.length() == 3 } } expect(true) { data.all { it.length() == 3 } }
expect(false) { data.all { it.startsWith("b") } } expect(false) { data.all { it.startsWith("b") } }
expect(true) { empty.all { it.startsWith("b") } } expect(true) { empty.all { it.startsWith("b") } }
} }
Test fun none() { @Test
fun none() {
expect(false) { data.none() } expect(false) { data.none() }
expect(true) { empty.none() } expect(true) { empty.none() }
expect(false) { data.none { it.length() == 3 } } expect(false) { data.none { it.length() == 3 } }
@@ -125,7 +137,8 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
expect(true) { empty.none { it.startsWith("b") } } expect(true) { empty.none { it.startsWith("b") } }
} }
Test fun filter() { @Test
fun filter() {
val foo = data.filter { it.startsWith("f") } val foo = data.filter { it.startsWith("f") }
expect(true) { foo is List<String> } expect(true) { foo is List<String> }
expect(true) { foo.all { it.startsWith("f") } } expect(true) { foo.all { it.startsWith("f") } }
@@ -133,7 +146,8 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertEquals(listOf("foo"), foo) assertEquals(listOf("foo"), foo)
} }
Test fun drop() { @Test
fun drop() {
val foo = data.drop(1) val foo = data.drop(1)
expect(true) { foo is List<String> } expect(true) { foo is List<String> }
expect(true) { foo.all { it.startsWith("b") } } expect(true) { foo.all { it.startsWith("b") } }
@@ -141,7 +155,8 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertEquals(listOf("bar"), foo) assertEquals(listOf("bar"), foo)
} }
Test fun dropWhile() { @Test
fun dropWhile() {
val foo = data.dropWhile { it[0] == 'f' } val foo = data.dropWhile { it[0] == 'f' }
expect(true) { foo is List<String> } expect(true) { foo is List<String> }
expect(true) { foo.all { it.startsWith("b") } } expect(true) { foo.all { it.startsWith("b") } }
@@ -149,7 +164,8 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertEquals(listOf("bar"), foo) assertEquals(listOf("bar"), foo)
} }
Test fun filterNot() { @Test
fun filterNot() {
val notFoo = data.filterNot { it.startsWith("f") } val notFoo = data.filterNot { it.startsWith("f") }
expect(true) { notFoo is List<String> } expect(true) { notFoo is List<String> }
expect(true) { notFoo.none { it.startsWith("f") } } expect(true) { notFoo.none { it.startsWith("f") } }
@@ -157,20 +173,23 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertEquals(listOf("bar"), notFoo) assertEquals(listOf("bar"), notFoo)
} }
Test fun forEach() { @Test
fun forEach() {
var count = 0 var count = 0
data.forEach { count += it.length() } data.forEach { count += it.length() }
assertEquals(6, count) assertEquals(6, count)
} }
Test fun contains() { @Test
fun contains() {
assertTrue(data.contains("foo")) assertTrue(data.contains("foo"))
assertTrue("bar" in data) assertTrue("bar" in data)
assertTrue("baz" !in data) assertTrue("baz" !in data)
assertFalse("baz" in empty) assertFalse("baz" in empty)
} }
Test fun single() { @Test
fun single() {
fails { data.single() } fails { data.single() }
fails { empty.single() } fails { empty.single() }
expect("foo") { data.single { it.startsWith("f") } } expect("foo") { data.single { it.startsWith("f") } }
@@ -180,7 +199,7 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
} }
} }
Test @Test
fun singleOrNull() { fun singleOrNull() {
expect(null) { data.singleOrNull() } expect(null) { data.singleOrNull() }
expect(null) { empty.singleOrNull() } expect(null) { empty.singleOrNull() }
@@ -191,7 +210,7 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
} }
} }
Test @Test
fun map() { fun map() {
val lengths = data.map { it.length() } val lengths = data.map { it.length() }
assertTrue { assertTrue {
@@ -201,38 +220,38 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertEquals(listOf(3, 3), lengths) assertEquals(listOf(3, 3), lengths)
} }
Test @Test
fun flatten() { fun flatten() {
assertEquals(listOf(0, 1, 2, 3, 0, 1, 2, 3), data.map { 0..it.length() }.flatten()) assertEquals(listOf(0, 1, 2, 3, 0, 1, 2, 3), data.map { 0..it.length() }.flatten())
} }
Test @Test
fun mapIndexed() { fun mapIndexed() {
val shortened = data.mapIndexed { index, value -> value.substring(0..index) } val shortened = data.mapIndexed { index, value -> value.substring(0..index) }
assertEquals(2, shortened.size()) assertEquals(2, shortened.size())
assertEquals(listOf("f", "ba"), shortened) assertEquals(listOf("f", "ba"), shortened)
} }
Test @Test
fun withIndex() { fun withIndex() {
val indexed = data.withIndex().map { it.value.substring(0..it.index) } val indexed = data.withIndex().map { it.value.substring(0..it.index) }
assertEquals(2, indexed.size()) assertEquals(2, indexed.size())
assertEquals(listOf("f", "ba"), indexed) assertEquals(listOf("f", "ba"), indexed)
} }
Test @Test
fun max() { fun max() {
expect("foo") { data.max() } expect("foo") { data.max() }
expect("bar") { data.maxBy { it.last() } } expect("bar") { data.maxBy { it.last() } }
} }
Test @Test
fun min() { fun min() {
expect("bar") { data.min() } expect("bar") { data.min() }
expect("foo") { data.minBy { it.last() } } expect("foo") { data.minBy { it.last() } }
} }
Test @Test
fun count() { fun count() {
expect(2) { data.count() } expect(2) { data.count() }
expect(0) { empty.count() } expect(0) { empty.count() }
@@ -244,7 +263,7 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
expect(0) { empty.count { it.startsWith("x") } } expect(0) { empty.count { it.startsWith("x") } }
} }
Test @Test
fun sumBy() { fun sumBy() {
expect(6) { data.sumBy { it.length() } } expect(6) { data.sumBy { it.length() } }
expect(0) { empty.sumBy { it.length() } } expect(0) { empty.sumBy { it.length() } }
@@ -253,7 +272,7 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
expect(0.0) { empty.sumByDouble { it.length().toDouble() / 2 } } expect(0.0) { empty.sumByDouble { it.length().toDouble() / 2 } }
} }
Test @Test
fun withIndices() { fun withIndices() {
var index = 0 var index = 0
for ((i, d) in data.withIndex()) { for ((i, d) in data.withIndex()) {
@@ -264,19 +283,19 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertEquals(data.count(), index) assertEquals(data.count(), index)
} }
Test @Test
fun fold() { fun fold() {
expect(231) { data.fold(1, { a, b -> a + if (b == "foo") 200 else 30 }) } expect(231) { data.fold(1, { a, b -> a + if (b == "foo") 200 else 30 }) }
} }
Test @Test
fun reduce() { fun reduce() {
val reduced = data.reduce { a, b -> a + b } val reduced = data.reduce { a, b -> a + b }
assertEquals(6, reduced.length()) assertEquals(6, reduced.length())
assertTrue(reduced == "foobar" || reduced == "barfoo") assertTrue(reduced == "foobar" || reduced == "barfoo")
} }
Test @Test
fun mapAndJoinToString() { fun mapAndJoinToString() {
val result = data.joinToString(separator = "-") { it.toUpperCase() } val result = data.joinToString(separator = "-") { it.toUpperCase() }
assertEquals("FOO-BAR", result) assertEquals("FOO-BAR", result)
@@ -288,16 +307,16 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertFalse(result === data) assertFalse(result === data)
} }
Test @Test
fun plusElement() = testPlus { it + "zoo" + "g" } fun plusElement() = testPlus { it + "zoo" + "g" }
Test @Test
fun plusCollection() = testPlus { it + listOf("zoo", "g") } fun plusCollection() = testPlus { it + listOf("zoo", "g") }
Test @Test
fun plusArray() = testPlus { it + arrayOf("zoo", "g") } fun plusArray() = testPlus { it + arrayOf("zoo", "g") }
Test @Test
fun plusSequence() = testPlus { it + sequenceOf("zoo", "g") } fun plusSequence() = testPlus { it + sequenceOf("zoo", "g") }
Test @Test
fun plusAssign() { fun plusAssign() {
// lets use a mutable variable // lets use a mutable variable
var result: Iterable<String> = data var result: Iterable<String> = data
@@ -308,31 +327,31 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
assertEquals(listOf("foo", "bar", "foo", "beer", "cheese", "wine", "zoo", "g"), result) assertEquals(listOf("foo", "bar", "foo", "beer", "cheese", "wine", "zoo", "g"), result)
} }
Test @Test
fun minusElement() { fun minusElement() {
val result = data - "foo" - "g" val result = data - "foo" - "g"
assertEquals(listOf("bar"), result) assertEquals(listOf("bar"), result)
} }
Test @Test
fun minusCollection() { fun minusCollection() {
val result = data - listOf("foo", "g") val result = data - listOf("foo", "g")
assertEquals(listOf("bar"), result) assertEquals(listOf("bar"), result)
} }
Test @Test
fun minusArray() { fun minusArray() {
val result = data - arrayOf("foo", "g") val result = data - arrayOf("foo", "g")
assertEquals(listOf("bar"), result) assertEquals(listOf("bar"), result)
} }
Test @Test
fun minusSequence() { fun minusSequence() {
val result = data - sequenceOf("foo", "g") val result = data - sequenceOf("foo", "g")
assertEquals(listOf("bar"), result) assertEquals(listOf("bar"), result)
} }
Test @Test
fun minusAssign() { fun minusAssign() {
// lets use a mutable variable // lets use a mutable variable
var result: Iterable<String> = data var result: Iterable<String> = data
@@ -6,7 +6,7 @@ import java.util.*
class IteratorsJVMTest { class IteratorsJVMTest {
test fun testEnumeration() { @test fun testEnumeration() {
val v = Vector<Int>() val v = Vector<Int>()
for (i in 1..5) for (i in 1..5)
v.add(i) v.add(i)
@@ -4,7 +4,7 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class IteratorsTest { class IteratorsTest {
test fun iterationOverIterator() { @test fun iterationOverIterator() {
val c = listOf(0, 1, 2, 3, 4, 5) val c = listOf(0, 1, 2, 3, 4, 5)
var s = "" var s = ""
for (i in c.iterator()) { for (i in c.iterator()) {
@@ -11,7 +11,8 @@ class ListBinarySearchTest {
val comparator = compareBy<IncomparableDataItem<Int>?> { it?.value } val comparator = compareBy<IncomparableDataItem<Int>?> { it?.value }
Test fun binarySearchByElement() { @Test
fun binarySearchByElement() {
val list = values val list = values
list.forEachIndexed { index, item -> list.forEachIndexed { index, item ->
assertEquals(index, list.binarySearch(item)) assertEquals(index, list.binarySearch(item))
@@ -25,7 +26,8 @@ class ListBinarySearchTest {
} }
} }
Test fun binarySearchByElementNullable() { @Test
fun binarySearchByElementNullable() {
val list = listOf(null) + values val list = listOf(null) + values
list.forEachIndexed { index, item -> list.forEachIndexed { index, item ->
assertEquals(index, list.binarySearch(item)) assertEquals(index, list.binarySearch(item))
@@ -37,7 +39,8 @@ class ListBinarySearchTest {
} }
} }
Test fun binarySearchWithComparator() { @Test
fun binarySearchWithComparator() {
val list = values map { IncomparableDataItem(it) } val list = values map { IncomparableDataItem(it) }
list.forEachIndexed { index, item -> list.forEachIndexed { index, item ->
@@ -52,7 +55,8 @@ class ListBinarySearchTest {
} }
} }
Test fun binarySearchByKey() { @Test
fun binarySearchByKey() {
val list = values map { IncomparableDataItem(it) } val list = values map { IncomparableDataItem(it) }
list.forEachIndexed { index, item -> list.forEachIndexed { index, item ->
@@ -68,7 +72,8 @@ class ListBinarySearchTest {
} }
Test fun binarySearchByKeyWithComparator() { @Test
fun binarySearchByKeyWithComparator() {
val list = values map { IncomparableDataItem(IncomparableDataItem(it)) } val list = values map { IncomparableDataItem(IncomparableDataItem(it)) }
list.forEachIndexed { index, item -> list.forEachIndexed { index, item ->
@@ -87,7 +92,8 @@ class ListBinarySearchTest {
} }
} }
Test fun binarySearchByMultipleKeys() { @Test
fun binarySearchByMultipleKeys() {
val list = values.flatMap { v1 -> values.map { v2 -> Pair(v1, v2) } } val list = values.flatMap { v1 -> values.map { v2 -> Pair(v1, v2) } }
list.forEachIndexed { index, item -> list.forEachIndexed { index, item ->
@@ -7,17 +7,20 @@ class ListSpecificTest {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val empty = listOf<String>() val empty = listOf<String>()
Test fun _toString() { @Test
fun _toString() {
assertEquals("[foo, bar]", data.toString()) assertEquals("[foo, bar]", data.toString())
} }
Test fun tail() { @Test
fun tail() {
val data = listOf("foo", "bar", "whatnot") val data = listOf("foo", "bar", "whatnot")
val actual = data.drop(1) val actual = data.drop(1)
assertEquals(listOf("bar", "whatnot"), actual) assertEquals(listOf("bar", "whatnot"), actual)
} }
Test fun slice() { @Test
fun slice() {
val list = listOf('A', 'B', 'C', 'D') val list = listOf('A', 'B', 'C', 'D')
// ABCD // ABCD
// 0123 // 0123
@@ -28,7 +31,8 @@ class ListSpecificTest {
assertEquals(listOf('C', 'A', 'D'), list.slice(iter)) assertEquals(listOf('C', 'A', 'D'), list.slice(iter))
} }
Test fun getOr() { @Test
fun getOr() {
expect("foo") { data.get(0) } expect("foo") { data.get(0) }
expect("bar") { data.get(1) } expect("bar") { data.get(1) }
fails { data.get(2) } fails { data.get(2) }
@@ -44,12 +48,14 @@ class ListSpecificTest {
} }
Test fun lastIndex() { @Test
fun lastIndex() {
assertEquals(-1, empty.lastIndex) assertEquals(-1, empty.lastIndex)
assertEquals(1, data.lastIndex) assertEquals(1, data.lastIndex)
} }
Test fun mutableList() { @Test
fun mutableList() {
val items = listOf("beverage", "location", "name") val items = listOf("beverage", "location", "name")
var list = listOf<String>() var list = listOf<String>()
@@ -61,7 +67,8 @@ class ListSpecificTest {
assertEquals("beverage,location,name", list.join(",")) assertEquals("beverage,location,name", list.join(","))
} }
Test fun testNullToString() { @Test
fun testNullToString() {
assertEquals("[null]", listOf<String?>(null).toString()) assertEquals("[null]", listOf<String?>(null).toString())
} }
} }
@@ -6,7 +6,7 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class MapJVMTest { class MapJVMTest {
test fun createSortedMap() { @test fun createSortedMap() {
val map = sortedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1)) val map = sortedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
assertEquals(1, map["a"]) assertEquals(1, map["a"])
assertEquals(2, map["b"]) assertEquals(2, map["b"])
@@ -14,7 +14,7 @@ class MapJVMTest {
assertEquals(listOf("a", "b", "c"), map.keySet().toList()) assertEquals(listOf("a", "b", "c"), map.keySet().toList())
} }
test fun toSortedMap() { @test fun toSortedMap() {
val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1)) val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
val sorted = map.toSortedMap() val sorted = map.toSortedMap()
assertEquals(1, sorted["a"]) assertEquals(1, sorted["a"])
@@ -23,7 +23,7 @@ class MapJVMTest {
assertEquals(listOf("a", "b", "c"), sorted.keySet().toList()) assertEquals(listOf("a", "b", "c"), sorted.keySet().toList())
} }
test fun toSortedMapWithComparator() { @test fun toSortedMapWithComparator() {
val map = mapOf(Pair("c", 3), Pair("bc", 2), Pair("bd", 4), Pair("abc", 1)) val map = mapOf(Pair("c", 3), Pair("bc", 2), Pair("bd", 4), Pair("abc", 1))
val sorted = map.toSortedMap(compareBy<String> { it.length() } thenBy { it }) val sorted = map.toSortedMap(compareBy<String> { it.length() } thenBy { it })
assertEquals(listOf("c", "bc", "bd", "abc"), sorted.keySet().toList()) assertEquals(listOf("c", "bc", "bd", "abc"), sorted.keySet().toList())
@@ -32,7 +32,7 @@ class MapJVMTest {
assertEquals(3, sorted["c"]) assertEquals(3, sorted["c"])
} }
test fun toProperties() { @test fun toProperties() {
val map = mapOf("a" to "A", "b" to "B") val map = mapOf("a" to "A", "b" to "B")
val prop = map.toProperties() val prop = map.toProperties()
assertEquals(2, prop.size()) assertEquals(2, prop.size())
@@ -40,7 +40,7 @@ class MapJVMTest {
assertEquals("B", prop.getProperty("b", "fail")) assertEquals("B", prop.getProperty("b", "fail"))
} }
test fun getOrPutFailsOnConcurrentMap() { @test fun getOrPutFailsOnConcurrentMap() {
val map = ConcurrentHashMap<String, Int>() val map = ConcurrentHashMap<String, Int>()
fails { fails {
+52 -52
View File
@@ -9,7 +9,7 @@ import org.junit.Test as test
class MapTest { class MapTest {
test fun getOrElse() { @test fun getOrElse() {
val data = mapOf<String, Int>() val data = mapOf<String, Int>()
val a = data.getOrElse("foo") { 2 } val a = data.getOrElse("foo") { 2 }
assertEquals(2, a) assertEquals(2, a)
@@ -23,7 +23,7 @@ class MapTest {
assertEquals(null, c) assertEquals(null, c)
} }
test fun getOrImplicitDefault() { @test fun getOrImplicitDefault() {
val data: MutableMap<String, Int> = hashMapOf("bar" to 1) val data: MutableMap<String, Int> = hashMapOf("bar" to 1)
assertTrue(fails { data.getOrImplicitDefault("foo") } is NoSuchElementException) assertTrue(fails { data.getOrImplicitDefault("foo") } is NoSuchElementException)
assertEquals(1, data.getOrImplicitDefault("bar")) assertEquals(1, data.getOrImplicitDefault("bar"))
@@ -44,7 +44,7 @@ class MapTest {
assertEquals(42, withReplacedDefault.getOrImplicitDefault("loop")) assertEquals(42, withReplacedDefault.getOrImplicitDefault("loop"))
} }
test fun getOrPut() { @test fun getOrPut() {
val data = hashMapOf<String, Int>() val data = hashMapOf<String, Int>()
val a = data.getOrPut("foo") { 2 } val a = data.getOrPut("foo") { 2 }
assertEquals(2, a) assertEquals(2, a)
@@ -59,13 +59,13 @@ class MapTest {
assertEquals(null, c) assertEquals(null, c)
} }
test fun sizeAndEmpty() { @test fun sizeAndEmpty() {
val data = hashMapOf<String, Int>() val data = hashMapOf<String, Int>()
assertTrue { data.none() } assertTrue { data.none() }
assertEquals(data.size(), 0) assertEquals(data.size(), 0)
} }
test fun setViaIndexOperators() { @test fun setViaIndexOperators() {
val map = hashMapOf<String, String>() val map = hashMapOf<String, String>()
assertTrue { map.none() } assertTrue { map.none() }
assertEquals(map.size(), 0) assertEquals(map.size(), 0)
@@ -77,7 +77,7 @@ class MapTest {
assertEquals("James", map["name"]) assertEquals("James", map["name"])
} }
test fun iterate() { @test fun iterate() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val list = arrayListOf<String>() val list = arrayListOf<String>()
for (e in map) { for (e in map) {
@@ -89,13 +89,13 @@ class MapTest {
assertEquals("beverage,beer,location,Mells,name,James", list.join(",")) assertEquals("beverage,beer,location,Mells,name,James", list.join(","))
} }
test fun stream() { @test fun stream() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val named = map.asSequence().filter { it.key == "name" }.single() val named = map.asSequence().filter { it.key == "name" }.single()
assertEquals("James", named.value) assertEquals("James", named.value)
} }
test fun iterateWithProperties() { @test fun iterateWithProperties() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val list = arrayListOf<String>() val list = arrayListOf<String>()
for (e in map) { for (e in map) {
@@ -107,7 +107,7 @@ class MapTest {
assertEquals("beverage,beer,location,Mells,name,James", list.join(",")) assertEquals("beverage,beer,location,Mells,name,James", list.join(","))
} }
test fun iterateWithExtraction() { @test fun iterateWithExtraction() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val list = arrayListOf<String>() val list = arrayListOf<String>()
for ((key, value) in map) { for ((key, value) in map) {
@@ -119,20 +119,20 @@ class MapTest {
assertEquals("beverage,beer,location,Mells,name,James", list.join(",")) assertEquals("beverage,beer,location,Mells,name,James", list.join(","))
} }
test fun contains() { @test fun contains() {
val map = mapOf("a" to 1, "b" to 2) val map = mapOf("a" to 1, "b" to 2)
assertTrue("a" in map) assertTrue("a" in map)
assertTrue("c" !in map) assertTrue("c" !in map)
} }
test fun map() { @test fun map() {
val m1 = mapOf("beverage" to "beer", "location" to "Mells") val m1 = mapOf("beverage" to "beer", "location" to "Mells")
val list = m1.map { it.value + " rocks" } val list = m1.map { it.value + " rocks" }
assertEquals(listOf("beer rocks", "Mells rocks"), list) assertEquals(listOf("beer rocks", "Mells rocks"), list)
} }
test fun mapValues() { @test fun mapValues() {
val m1 = mapOf("beverage" to "beer", "location" to "Mells") val m1 = mapOf("beverage" to "beer", "location" to "Mells")
val m2 = m1.mapValues { it.value + "2" } val m2 = m1.mapValues { it.value + "2" }
@@ -140,7 +140,7 @@ class MapTest {
assertEquals("Mells2", m2["location"]) assertEquals("Mells2", m2["location"])
} }
test fun mapKeys() { @test fun mapKeys() {
val m1 = mapOf("beverage" to "beer", "location" to "Mells") val m1 = mapOf("beverage" to "beer", "location" to "Mells")
val m2 = m1.mapKeys { it.key + "2" } val m2 = m1.mapKeys { it.key + "2" }
@@ -148,21 +148,21 @@ class MapTest {
assertEquals("Mells", m2["location2"]) assertEquals("Mells", m2["location2"])
} }
test fun createUsingPairs() { @test fun createUsingPairs() {
val map = mapOf(Pair("a", 1), Pair("b", 2)) val map = mapOf(Pair("a", 1), Pair("b", 2))
assertEquals(2, map.size()) assertEquals(2, map.size())
assertEquals(1, map["a"]) assertEquals(1, map["a"])
assertEquals(2, map["b"]) assertEquals(2, map["b"])
} }
test fun createFromIterable() { @test fun createFromIterable() {
val map = listOf(Pair("a", 1), Pair("b", 2)).toMap() val map = listOf(Pair("a", 1), Pair("b", 2)).toMap()
assertEquals(2, map.size()) assertEquals(2, map.size())
assertEquals(1, map.get("a")) assertEquals(1, map.get("a"))
assertEquals(2, map.get("b")) assertEquals(2, map.get("b"))
} }
test fun createWithSelector() { @test fun createWithSelector() {
val map = listOf("a", "bb", "ccc").toMap { it.length() } val map = listOf("a", "bb", "ccc").toMap { it.length() }
assertEquals(3, map.size()) assertEquals(3, map.size())
assertEquals("a", map.get(1)) assertEquals("a", map.get(1))
@@ -170,14 +170,14 @@ class MapTest {
assertEquals("ccc", map.get(3)) assertEquals("ccc", map.get(3))
} }
test fun createWithSelectorAndOverwrite() { @test fun createWithSelectorAndOverwrite() {
val map = listOf("aa", "bb", "ccc").toMap { it.length() } val map = listOf("aa", "bb", "ccc").toMap { it.length() }
assertEquals(2, map.size()) assertEquals(2, map.size())
assertEquals("bb", map.get(2)) assertEquals("bb", map.get(2))
assertEquals("ccc", map.get(3)) assertEquals("ccc", map.get(3))
} }
test fun createWithSelectorForKeyAndValue() { @test fun createWithSelectorForKeyAndValue() {
val map = listOf("a", "bb", "ccc").toMap({ it.length() }, { it.toUpperCase() }) val map = listOf("a", "bb", "ccc").toMap({ it.length() }, { it.toUpperCase() })
assertEquals(3, map.size()) assertEquals(3, map.size())
assertEquals("A", map.get(1)) assertEquals("A", map.get(1))
@@ -185,14 +185,14 @@ class MapTest {
assertEquals("CCC", map.get(3)) assertEquals("CCC", map.get(3))
} }
test fun createUsingTo() { @test fun createUsingTo() {
val map = mapOf("a" to 1, "b" to 2) val map = mapOf("a" to 1, "b" to 2)
assertEquals(2, map.size()) assertEquals(2, map.size())
assertEquals(1, map["a"]) assertEquals(1, map["a"])
assertEquals(2, map["b"]) assertEquals(2, map["b"])
} }
test fun createLinkedMap() { @test fun createLinkedMap() {
val map = linkedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1)) val map = linkedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
assertEquals(1, map["a"]) assertEquals(1, map["a"])
assertEquals(2, map["b"]) assertEquals(2, map["b"])
@@ -200,7 +200,7 @@ class MapTest {
assertEquals(listOf("c", "b", "a"), map.keySet().toList()) assertEquals(listOf("c", "b", "a"), map.keySet().toList())
} }
test fun filter() { @test fun filter() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
val filteredByKey = map.filter { it.key == "b" } val filteredByKey = map.filter { it.key == "b" }
assertEquals(1, filteredByKey.size()) assertEquals(1, filteredByKey.size())
@@ -223,7 +223,7 @@ class MapTest {
assertEquals(2, filteredByValue2["a"]) assertEquals(2, filteredByValue2["a"])
} }
test fun any() { @test fun any() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
assertTrue(map.any()) assertTrue(map.any())
assertFalse(emptyMap<String, Int>().any()) assertFalse(emptyMap<String, Int>().any())
@@ -235,7 +235,7 @@ class MapTest {
assertFalse(map.any { it.value == 5 }) assertFalse(map.any { it.value == 5 })
} }
test fun all() { @test fun all() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
assertTrue(map.all { it.key != "d" }) assertTrue(map.all { it.key != "d" })
assertTrue(emptyMap<String, Int>().all { it.key == "d" }) assertTrue(emptyMap<String, Int>().all { it.key == "d" })
@@ -244,7 +244,7 @@ class MapTest {
assertFalse(map.all { it.value == 2 }) assertFalse(map.all { it.value == 2 })
} }
test fun countBy() { @test fun countBy() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
assertEquals(3, map.count()) assertEquals(3, map.count())
@@ -255,7 +255,7 @@ class MapTest {
assertEquals(2, filteredByValue) assertEquals(2, filteredByValue)
} }
test fun filterNot() { @test fun filterNot() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
val filteredByKey = map.filterNot { it.key == "b" } val filteredByKey = map.filterNot { it.key == "b" }
assertEquals(2, filteredByKey.size()) assertEquals(2, filteredByKey.size())
@@ -277,18 +277,18 @@ class MapTest {
assertEquals(3, map["c"]) assertEquals(3, map["c"])
} }
test fun plusAssign() = testPlusAssign { @test fun plusAssign() = testPlusAssign {
it += "b" to 4 it += "b" to 4
it += "c" to 3 it += "c" to 3
} }
test fun plusAssignList() = testPlusAssign { it += listOf("c" to 3, "b" to 4) } @test fun plusAssignList() = testPlusAssign { it += listOf("c" to 3, "b" to 4) }
test fun plusAssignArray() = testPlusAssign { it += arrayOf("c" to 3, "b" to 4) } @test fun plusAssignArray() = testPlusAssign { it += arrayOf("c" to 3, "b" to 4) }
test fun plusAssignSequence() = testPlusAssign { it += sequenceOf("c" to 3, "b" to 4) } @test fun plusAssignSequence() = testPlusAssign { it += sequenceOf("c" to 3, "b" to 4) }
test fun plusAssignMap() = testPlusAssign { it += mapOf("c" to 3, "b" to 4) } @test fun plusAssignMap() = testPlusAssign { it += mapOf("c" to 3, "b" to 4) }
fun testPlus(doPlus: (Map<String, Int>) -> Map<String, Int>) { fun testPlus(doPlus: (Map<String, Int>) -> Map<String, Int>) {
val original = mapOf("A" to 1, "B" to 2) val original = mapOf("A" to 1, "B" to 2)
@@ -299,15 +299,15 @@ class MapTest {
assertEquals(3, extended["C"]) assertEquals(3, extended["C"])
} }
test fun plus() = testPlus { it + ("C" to 3) + ("B" to 4) } @test fun plus() = testPlus { it + ("C" to 3) + ("B" to 4) }
test fun plusList() = testPlus { it + listOf("C" to 3, "B" to 4) } @test fun plusList() = testPlus { it + listOf("C" to 3, "B" to 4) }
test fun plusArray() = testPlus { it + arrayOf("C" to 3, "B" to 4) } @test fun plusArray() = testPlus { it + arrayOf("C" to 3, "B" to 4) }
test fun plusSequence() = testPlus { it + sequenceOf("C" to 3, "B" to 4) } @test fun plusSequence() = testPlus { it + sequenceOf("C" to 3, "B" to 4) }
test fun plusMap() = testPlus { it + mapOf("C" to 3, "B" to 4) } @test fun plusMap() = testPlus { it + mapOf("C" to 3, "B" to 4) }
fun testMinus(doMinus: (Map<String, Int>) -> Map<String, Int>) { fun testMinus(doMinus: (Map<String, Int>) -> Map<String, Int>) {
@@ -316,15 +316,15 @@ class MapTest {
assertEquals("A" to 1, shortened.entrySet().single().toPair()) assertEquals("A" to 1, shortened.entrySet().single().toPair())
} }
test fun minus() = testMinus { it - "B" - "C" } @test fun minus() = testMinus { it - "B" - "C" }
test fun minusList() = testMinus { it - listOf("B", "C") } @test fun minusList() = testMinus { it - listOf("B", "C") }
test fun minusArray() = testMinus { it - arrayOf("B", "C") } @test fun minusArray() = testMinus { it - arrayOf("B", "C") }
test fun minusSequence() = testMinus { it - sequenceOf("B", "C") } @test fun minusSequence() = testMinus { it - sequenceOf("B", "C") }
test fun minusSet() = testMinus { it - setOf("B", "C") } @test fun minusSet() = testMinus { it - setOf("B", "C") }
@@ -334,16 +334,16 @@ class MapTest {
assertEquals("A" to 1, original.entrySet().single().toPair()) assertEquals("A" to 1, original.entrySet().single().toPair())
} }
test fun minusAssign() = testMinusAssign { @test fun minusAssign() = testMinusAssign {
it -= "B" it -= "B"
it -= "C" it -= "C"
} }
test fun minusAssignList() = testMinusAssign { it -= listOf("B", "C") } @test fun minusAssignList() = testMinusAssign { it -= listOf("B", "C") }
test fun minusAssignArray() = testMinusAssign { it -= arrayOf("B", "C") } @test fun minusAssignArray() = testMinusAssign { it -= arrayOf("B", "C") }
test fun minusAssignSequence() = testMinusAssign { it -= sequenceOf("B", "C") } @test fun minusAssignSequence() = testMinusAssign { it -= sequenceOf("B", "C") }
fun testIdempotent(operation: (Map<String, Int>) -> Map<String, Int>) { fun testIdempotent(operation: (Map<String, Int>) -> Map<String, Int>) {
@@ -359,17 +359,17 @@ class MapTest {
} }
test fun plusEmptyList() = testIdempotent { it + listOf() } @test fun plusEmptyList() = testIdempotent { it + listOf() }
test fun minusEmptyList() = testIdempotent { it - listOf() } @test fun minusEmptyList() = testIdempotent { it - listOf() }
test fun plusEmptySet() = testIdempotent { it + setOf() } @test fun plusEmptySet() = testIdempotent { it + setOf() }
test fun minusEmptySet() = testIdempotent { it - setOf() } @test fun minusEmptySet() = testIdempotent { it - setOf() }
test fun plusAssignEmptyList() = testIdempotentAssign { it += listOf() } @test fun plusAssignEmptyList() = testIdempotentAssign { it += listOf() }
test fun minusAssignEmptyList() = testIdempotentAssign { it -= listOf() } @test fun minusAssignEmptyList() = testIdempotentAssign { it -= listOf() }
test fun plusAssignEmptySet() = testIdempotentAssign { it += setOf() } @test fun plusAssignEmptySet() = testIdempotentAssign { it += setOf() }
test fun minusAssignEmptySet() = testIdempotentAssign { it -= setOf() } @test fun minusAssignEmptySet() = testIdempotentAssign { it -= setOf() }
} }
@@ -10,7 +10,7 @@ class MutableCollectionTest {
// TODO: Use apply scope function // TODO: Use apply scope function
test fun addAll() { @test fun addAll() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
fun assertAdd(f: MutableList<String>.() -> Unit) = assertEquals(data, arrayListOf<String>().let { it.f(); it }) fun assertAdd(f: MutableList<String>.() -> Unit) = assertEquals(data, arrayListOf<String>().let { it.f(); it })
@@ -21,7 +21,7 @@ class MutableCollectionTest {
assertAdd { addAll(data.asSequence()) } assertAdd { addAll(data.asSequence()) }
} }
test fun removeAll() { @test fun removeAll() {
val content = arrayOf("foo", "bar", "bar") val content = arrayOf("foo", "bar", "bar")
val data = listOf("bar") val data = listOf("bar")
val expected = listOf("foo") val expected = listOf("foo")
@@ -35,7 +35,7 @@ class MutableCollectionTest {
} }
test fun retainAll() { @test fun retainAll() {
val content = arrayOf("foo", "bar", "bar") val content = arrayOf("foo", "bar", "bar")
val data = listOf("bar") val data = listOf("bar")
val expected = listOf("bar", "bar") val expected = listOf("bar", "bar")
@@ -25,7 +25,7 @@ import org.junit.Test as test
*/ */
class ReversedViewsJVMTest { class ReversedViewsJVMTest {
test fun testMutableSubList() { @test fun testMutableSubList() {
val original = arrayListOf(1, 2, 3, 4) val original = arrayListOf(1, 2, 3, 4)
val reversedSubList = original.asReversed().subList(1, 3) val reversedSubList = original.asReversed().subList(1, 3)
@@ -26,11 +26,11 @@ import org.junit.Test as test
class ReversedViewsTest { class ReversedViewsTest {
test fun testNullToString() { @test fun testNullToString() {
assertEquals("[null]", listOf<String?>(null).asReversed().toString()) assertEquals("[null]", listOf<String?>(null).asReversed().toString())
} }
test fun testBehavior() { @test fun testBehavior() {
val original = listOf(2L, 3L, Long.MAX_VALUE) val original = listOf(2L, 3L, Long.MAX_VALUE)
val reversed = original.reversed() val reversed = original.reversed()
compare(reversed, original.asReversed()) { compare(reversed, original.asReversed()) {
@@ -38,12 +38,12 @@ class ReversedViewsTest {
} }
} }
test fun testSimple() { @test fun testSimple() {
assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed()) assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed())
assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed().toList()) assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed().toList())
} }
test fun testRandomAccess() { @test fun testRandomAccess() {
val reversed = listOf(1, 2, 3).asReversed() val reversed = listOf(1, 2, 3).asReversed()
assertEquals(3, reversed[0]) assertEquals(3, reversed[0])
@@ -51,40 +51,40 @@ class ReversedViewsTest {
assertEquals(1, reversed[2]) assertEquals(1, reversed[2])
} }
test fun testDoubleReverse() { @test fun testDoubleReverse() {
assertEquals(listOf(1, 2, 3), listOf(1, 2, 3).asReversed().asReversed()) assertEquals(listOf(1, 2, 3), listOf(1, 2, 3).asReversed().asReversed())
assertEquals(listOf(2, 3), listOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed()) assertEquals(listOf(2, 3), listOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed())
} }
test fun testEmpty() { @test fun testEmpty() {
assertEquals(emptyList<Int>(), emptyList<Int>().asReversed()) assertEquals(emptyList<Int>(), emptyList<Int>().asReversed())
} }
test fun testReversedSubList() { @test fun testReversedSubList() {
val reversed = (1..10).toList().asReversed() val reversed = (1..10).toList().asReversed()
assertEquals(listOf(9, 8, 7), reversed.subList(1, 4)) assertEquals(listOf(9, 8, 7), reversed.subList(1, 4))
} }
test fun testMutableSimple() { @test fun testMutableSimple() {
assertEquals(listOf(3, 2, 1), arrayListOf(1, 2, 3).asReversed()) assertEquals(listOf(3, 2, 1), arrayListOf(1, 2, 3).asReversed())
assertEquals(listOf(3, 2, 1), arrayListOf(1, 2, 3).asReversed().toList()) assertEquals(listOf(3, 2, 1), arrayListOf(1, 2, 3).asReversed().toList())
} }
test fun testMutableDoubleReverse() { @test fun testMutableDoubleReverse() {
assertEquals(listOf(1, 2, 3), arrayListOf(1, 2, 3).asReversed().asReversed()) assertEquals(listOf(1, 2, 3), arrayListOf(1, 2, 3).asReversed().asReversed())
assertEquals(listOf(2, 3), arrayListOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed()) assertEquals(listOf(2, 3), arrayListOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed())
} }
test fun testMutableEmpty() { @test fun testMutableEmpty() {
assertEquals(emptyList<Int>(), arrayListOf<Int>().asReversed()) assertEquals(emptyList<Int>(), arrayListOf<Int>().asReversed())
} }
test fun testMutableReversedSubList() { @test fun testMutableReversedSubList() {
val reversed = (1..10).toArrayList().asReversed() val reversed = (1..10).toArrayList().asReversed()
assertEquals(listOf(9, 8, 7), reversed.subList(1, 4)) assertEquals(listOf(9, 8, 7), reversed.subList(1, 4))
} }
test fun testMutableAdd() { @test fun testMutableAdd() {
val original = arrayListOf(1, 2, 3) val original = arrayListOf(1, 2, 3)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -97,7 +97,7 @@ class ReversedViewsTest {
assertEquals(listOf(0, 1, 2, 3, 4), original) assertEquals(listOf(0, 1, 2, 3, 4), original)
} }
test fun testMutableSet() { @test fun testMutableSet() {
val original = arrayListOf(1, 2, 3) val original = arrayListOf(1, 2, 3)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -109,7 +109,7 @@ class ReversedViewsTest {
assertEquals(listOf(300, 200, 100), reversed) assertEquals(listOf(300, 200, 100), reversed)
} }
test fun testMutableRemove() { @test fun testMutableRemove() {
val original = arrayListOf("a", "b", "c") val original = arrayListOf("a", "b", "c")
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -124,7 +124,7 @@ class ReversedViewsTest {
assertEquals(emptyList<String>(), original) assertEquals(emptyList<String>(), original)
} }
test fun testMutableRemoveByObj() { @test fun testMutableRemoveByObj() {
val original = arrayListOf("a", "b", "c") val original = arrayListOf("a", "b", "c")
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -133,7 +133,7 @@ class ReversedViewsTest {
assertEquals(listOf("b", "a"), reversed) assertEquals(listOf("b", "a"), reversed)
} }
test fun testMutableClear() { @test fun testMutableClear() {
val original = arrayListOf(1, 2, 3) val original = arrayListOf(1, 2, 3)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -143,17 +143,17 @@ class ReversedViewsTest {
assertEquals(emptyList<Int>(), original) assertEquals(emptyList<Int>(), original)
} }
test fun testContains() { @test fun testContains() {
assertTrue { 1 in listOf(1, 2, 3).asReversed() } assertTrue { 1 in listOf(1, 2, 3).asReversed() }
assertTrue { 1 in arrayListOf(1, 2, 3).asReversed() } assertTrue { 1 in arrayListOf(1, 2, 3).asReversed() }
} }
test fun testIndexOf() { @test fun testIndexOf() {
assertEquals(2, listOf(1, 2, 3).asReversed().indexOf(1)) assertEquals(2, listOf(1, 2, 3).asReversed().indexOf(1))
assertEquals(2, arrayListOf(1, 2, 3).asReversed().indexOf(1)) assertEquals(2, arrayListOf(1, 2, 3).asReversed().indexOf(1))
} }
test fun testBidirectionalModifications() { @test fun testBidirectionalModifications() {
val original = arrayListOf(1, 2, 3, 4) val original = arrayListOf(1, 2, 3, 4)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -166,7 +166,7 @@ class ReversedViewsTest {
assertEquals(listOf(3, 2), reversed) assertEquals(listOf(3, 2), reversed)
} }
test fun testGetIOOB() { @test fun testGetIOOB() {
val success = try { val success = try {
listOf(1, 2, 3).asReversed().get(3) listOf(1, 2, 3).asReversed().get(3)
true true
@@ -177,7 +177,7 @@ class ReversedViewsTest {
assertFalse(success) assertFalse(success)
} }
test fun testSetIOOB() { @test fun testSetIOOB() {
val success = try { val success = try {
arrayListOf(1, 2, 3).asReversed().set(3, 0) arrayListOf(1, 2, 3).asReversed().set(3, 0)
true true
@@ -188,7 +188,7 @@ class ReversedViewsTest {
assertFalse(success) assertFalse(success)
} }
test fun testAddIOOB() { @test fun testAddIOOB() {
val success = try { val success = try {
arrayListOf(1, 2, 3).asReversed().add(4, 0) arrayListOf(1, 2, 3).asReversed().add(4, 0)
true true
@@ -199,7 +199,7 @@ class ReversedViewsTest {
assertFalse(success) assertFalse(success)
} }
test fun testRemoveIOOB() { @test fun testRemoveIOOB() {
val success = try { val success = try {
arrayListOf(1, 2, 3).asReversed().remove(3) arrayListOf(1, 2, 3).asReversed().remove(3)
true true
@@ -5,7 +5,7 @@ import kotlin.test.assertEquals
class SequenceJVMTest { class SequenceJVMTest {
test fun filterIsInstance() { @test fun filterIsInstance() {
val src: Sequence<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde").asSequence() val src: Sequence<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde").asSequence()
val intValues: Sequence<Int> = src.filterIsInstance<Int>() val intValues: Sequence<Int> = src.filterIsInstance<Int>()
@@ -19,20 +19,20 @@ fun fibonacci(): Sequence<Int> {
public class SequenceTest { public class SequenceTest {
test fun filterEmptySequence() { @test fun filterEmptySequence() {
for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) { for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) {
assertEquals(0, sequence.filter { false }.count()) assertEquals(0, sequence.filter { false }.count())
assertEquals(0, sequence.filter { true }.count()) assertEquals(0, sequence.filter { true }.count())
} }
} }
test fun mapEmptySequence() { @test fun mapEmptySequence() {
for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) { for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) {
assertEquals(0, sequence.map { true }.count()) assertEquals(0, sequence.map { true }.count())
} }
} }
test fun requireNoNulls() { @test fun requireNoNulls() {
val sequence = sequenceOf<String?>("foo", "bar") val sequence = sequenceOf<String?>("foo", "bar")
val notNull = sequence.requireNoNulls() val notNull = sequence.requireNoNulls()
assertEquals(listOf("foo", "bar"), notNull.toList()) assertEquals(listOf("foo", "bar"), notNull.toList())
@@ -45,25 +45,25 @@ public class SequenceTest {
} }
} }
test fun filterNullable() { @test fun filterNullable() {
val data = sequenceOf(null, "foo", null, "bar") val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filter { it == null || it == "foo" } val filtered = data.filter { it == null || it == "foo" }
assertEquals(listOf(null, "foo", null), filtered.toList()) assertEquals(listOf(null, "foo", null), filtered.toList())
} }
test fun filterNot() { @test fun filterNot() {
val data = sequenceOf(null, "foo", null, "bar") val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filterNot { it == null } val filtered = data.filterNot { it == null }
assertEquals(listOf("foo", "bar"), filtered.toList()) assertEquals(listOf("foo", "bar"), filtered.toList())
} }
test fun filterNotNull() { @test fun filterNotNull() {
val data = sequenceOf(null, "foo", null, "bar") val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filterNotNull() val filtered = data.filterNotNull()
assertEquals(listOf("foo", "bar"), filtered.toList()) assertEquals(listOf("foo", "bar"), filtered.toList())
} }
test fun mapNotNull() { @test fun mapNotNull() {
val data = sequenceOf(null, "foo", null, "bar") val data = sequenceOf(null, "foo", null, "bar")
val foo = data.mapNotNull { it.length() } val foo = data.mapNotNull { it.length() }
assertEquals(listOf(3, 3), foo.toList()) assertEquals(listOf(3, 3), foo.toList())
@@ -73,60 +73,60 @@ public class SequenceTest {
} }
} }
test fun mapAndJoinToString() { @test fun mapAndJoinToString() {
assertEquals("3, 5, 8", fibonacci().withIndex().filter { it.index > 3 }.take(3).joinToString { it.value.toString() }) assertEquals("3, 5, 8", fibonacci().withIndex().filter { it.index > 3 }.take(3).joinToString { it.value.toString() })
} }
test fun withIndex() { @test fun withIndex() {
val data = sequenceOf("foo", "bar") val data = sequenceOf("foo", "bar")
val indexed = data.withIndex().map { it.value.substring(0..it.index) }.toList() val indexed = data.withIndex().map { it.value.substring(0..it.index) }.toList()
assertEquals(2, indexed.size()) assertEquals(2, indexed.size())
assertEquals(listOf("f", "ba"), indexed) assertEquals(listOf("f", "ba"), indexed)
} }
test fun filterAndTakeWhileExtractTheElementsWithinRange() { @test fun filterAndTakeWhileExtractTheElementsWithinRange() {
assertEquals(listOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList()) assertEquals(listOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList())
} }
test fun foldReducesTheFirstNElements() { @test fun foldReducesTheFirstNElements() {
val sum = { a: Int, b: Int -> a + b } val sum = { a: Int, b: Int -> a + b }
assertEquals(listOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum)) assertEquals(listOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum))
} }
test fun takeExtractsTheFirstNElements() { @test fun takeExtractsTheFirstNElements() {
assertEquals(listOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList()) assertEquals(listOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList())
} }
test fun mapAndTakeWhileExtractTheTransformedElements() { @test fun mapAndTakeWhileExtractTheTransformedElements() {
assertEquals(listOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList()) assertEquals(listOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList())
} }
test fun joinConcatenatesTheFirstNElementsAboveAThreshold() { @test fun joinConcatenatesTheFirstNElementsAboveAThreshold() {
assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.joinToString(separator = ", ", limit = 5)) assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.joinToString(separator = ", ", limit = 5))
} }
test fun drop() { @test fun drop() {
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).joinToString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(3).drop(4).joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(3).drop(4).joinToString(limit = 10))
} }
test fun take() { @test fun take() {
assertEquals("0, 1, 1, 2, 3, 5, 8", fibonacci().take(7).joinToString()) assertEquals("0, 1, 1, 2, 3, 5, 8", fibonacci().take(7).joinToString())
assertEquals("2, 3, 5, 8", fibonacci().drop(3).take(4).joinToString()) assertEquals("2, 3, 5, 8", fibonacci().drop(3).take(4).joinToString())
} }
test fun dropWhile() { @test fun dropWhile() {
assertEquals("233, 377, 610", fibonacci().dropWhile { it < 200 }.take(3).joinToString(limit = 10)) assertEquals("233, 377, 610", fibonacci().dropWhile { it < 200 }.take(3).joinToString(limit = 10))
assertEquals("", sequenceOf(1).dropWhile { it < 200 }.joinToString(limit = 10)) assertEquals("", sequenceOf(1).dropWhile { it < 200 }.joinToString(limit = 10))
} }
test fun merge() { @test fun merge() {
expect(listOf("ab", "bc", "cd")) { expect(listOf("ab", "bc", "cd")) {
sequenceOf("a", "b", "c").merge(sequenceOf("b", "c", "d")) { a, b -> a + b }.toList() sequenceOf("a", "b", "c").merge(sequenceOf("b", "c", "d")) { a, b -> a + b }.toList()
} }
} }
test fun toStringJoinsNoMoreThanTheFirstTenElements() { @test fun toStringJoinsNoMoreThanTheFirstTenElements() {
assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().joinToString(limit = 10)) assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().joinToString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.joinToString(limit = 10))
assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.joinToString()) assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.joinToString())
@@ -141,12 +141,12 @@ public class SequenceTest {
} }
test fun plusElement() = testPlus { it + "cheese" + "wine" } @test fun plusElement() = testPlus { it + "cheese" + "wine" }
test fun plusCollection() = testPlus { it + listOf("cheese", "wine") } @test fun plusCollection() = testPlus { it + listOf("cheese", "wine") }
test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") } @test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") }
test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") } @test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") }
test fun plusAssign() { @test fun plusAssign() {
// lets use a mutable variable // lets use a mutable variable
var seq = sequenceOf("a") var seq = sequenceOf("a")
seq += "foo" seq += "foo"
@@ -163,12 +163,12 @@ public class SequenceTest {
assertEquals(expected_, b.toList()) assertEquals(expected_, b.toList())
} }
test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" } @test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" }
test fun minusCollection() = testMinus { it - listOf("bar", "zoo") } @test fun minusCollection() = testMinus { it - listOf("bar", "zoo") }
test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") } @test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") }
test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") } @test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") }
test fun minusIsLazyIterated() { @test fun minusIsLazyIterated() {
val seq = sequenceOf("foo", "bar") val seq = sequenceOf("foo", "bar")
val list = arrayListOf<String>() val list = arrayListOf<String>()
val result = seq - list val result = seq - list
@@ -179,7 +179,7 @@ public class SequenceTest {
assertEquals(emptyList<String>(), result.toList()) assertEquals(emptyList<String>(), result.toList())
} }
test fun minusAssign() { @test fun minusAssign() {
// lets use a mutable variable of readonly list // lets use a mutable variable of readonly list
val data = sequenceOf("cheese", "foo", "beer", "cheese", "wine") val data = sequenceOf("cheese", "foo", "beer", "cheese", "wine")
var l = data var l = data
@@ -194,7 +194,7 @@ public class SequenceTest {
test fun iterationOverSequence() { @test fun iterationOverSequence() {
var s = "" var s = ""
for (i in sequenceOf(0, 1, 2, 3, 4, 5)) { for (i in sequenceOf(0, 1, 2, 3, 4, 5)) {
s += i.toString() s += i.toString()
@@ -202,7 +202,7 @@ public class SequenceTest {
assertEquals("012345", s) assertEquals("012345", s)
} }
test fun sequenceFromFunction() { @test fun sequenceFromFunction() {
var count = 3 var count = 3
val sequence = sequence { val sequence = sequence {
@@ -218,7 +218,7 @@ public class SequenceTest {
} }
} }
test fun sequenceFromFunctionWithInitialValue() { @test fun sequenceFromFunctionWithInitialValue() {
val values = sequence(3) { n -> if (n > 0) n - 1 else null } val values = sequence(3) { n -> if (n > 0) n - 1 else null }
val expected = listOf(3, 2, 1, 0) val expected = listOf(3, 2, 1, 0)
assertEquals(expected, values.toList()) assertEquals(expected, values.toList())
@@ -226,7 +226,7 @@ public class SequenceTest {
} }
test fun sequenceFromIterator() { @test fun sequenceFromIterator() {
val list = listOf(3, 2, 1, 0) val list = listOf(3, 2, 1, 0)
val iterator = list.iterator() val iterator = list.iterator()
val sequence = iterator.asSequence() val sequence = iterator.asSequence()
@@ -236,7 +236,7 @@ public class SequenceTest {
} }
} }
test fun makeSequenceOneTimeConstrained() { @test fun makeSequenceOneTimeConstrained() {
val sequence = sequenceOf(1, 2, 3, 4) val sequence = sequenceOf(1, 2, 3, 4)
sequence.toList() sequence.toList()
sequence.toList() sequence.toList()
@@ -256,13 +256,13 @@ public class SequenceTest {
return result return result
} }
test fun sequenceExtensions() { @test fun sequenceExtensions() {
val d = ArrayList<Int>() val d = ArrayList<Int>()
sequenceOf(0, 1, 2, 3, 4, 5).takeWhileTo(d, { i -> i < 4 }) sequenceOf(0, 1, 2, 3, 4, 5).takeWhileTo(d, { i -> i < 4 })
assertEquals(4, d.size()) assertEquals(4, d.size())
} }
test fun flatMapAndTakeExtractTheTransformedElements() { @test fun flatMapAndTakeExtractTheTransformedElements() {
val expected = listOf( val expected = listOf(
'3', // fibonacci(4) = 3 '3', // fibonacci(4) = 3
'5', // fibonacci(5) = 5 '5', // fibonacci(5) = 5
@@ -276,51 +276,51 @@ public class SequenceTest {
assertEquals(expected, fibonacci().drop(4).flatMap { it.toString().asSequence() }.take(10).toList()) assertEquals(expected, fibonacci().drop(4).flatMap { it.toString().asSequence() }.take(10).toList())
} }
test fun flatMap() { @test fun flatMap() {
val result = sequenceOf(1, 2).flatMap { sequenceOf(0..it) } val result = sequenceOf(1, 2).flatMap { sequenceOf(0..it) }
assertEquals(listOf(0, 1, 0, 1, 2), result.toList()) assertEquals(listOf(0, 1, 0, 1, 2), result.toList())
} }
test fun flatMapOnEmpty() { @test fun flatMapOnEmpty() {
val result = sequenceOf<Int>().flatMap { sequenceOf(0..it) } val result = sequenceOf<Int>().flatMap { sequenceOf(0..it) }
assertTrue(result.none()) assertTrue(result.none())
} }
test fun flatMapWithEmptyItems() { @test fun flatMapWithEmptyItems() {
val result = sequenceOf(1, 2, 4).flatMap { if (it == 2) sequenceOf<Int>() else sequenceOf(it - 1..it) } val result = sequenceOf(1, 2, 4).flatMap { if (it == 2) sequenceOf<Int>() else sequenceOf(it - 1..it) }
assertEquals(listOf(0, 1, 3, 4), result.toList()) assertEquals(listOf(0, 1, 3, 4), result.toList())
} }
test fun flatten() { @test fun flatten() {
val data = sequenceOf(1, 2).map { sequenceOf(0..it) } val data = sequenceOf(1, 2).map { sequenceOf(0..it) }
assertEquals(listOf(0, 1, 0, 1, 2), data.flatten().toList()) assertEquals(listOf(0, 1, 0, 1, 2), data.flatten().toList())
} }
test fun distinct() { @test fun distinct() {
val sequence = fibonacci().dropWhile { it < 10 }.take(20) val sequence = fibonacci().dropWhile { it < 10 }.take(20)
assertEquals(listOf(1, 2, 3, 0), sequence.map { it % 4 }.distinct().toList()) assertEquals(listOf(1, 2, 3, 0), sequence.map { it % 4 }.distinct().toList())
} }
test fun distinctBy() { @test fun distinctBy() {
val sequence = fibonacci().dropWhile { it < 10 }.take(20) val sequence = fibonacci().dropWhile { it < 10 }.take(20)
assertEquals(listOf(13, 34, 55, 144), sequence.distinctBy { it % 4 }.toList()) assertEquals(listOf(13, 34, 55, 144), sequence.distinctBy { it % 4 }.toList())
} }
test fun unzip() { @test fun unzip() {
val seq = sequenceOf(1 to 'a', 2 to 'b', 3 to 'c') val seq = sequenceOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = seq.unzip() val (ints, chars) = seq.unzip()
assertEquals(listOf(1, 2, 3), ints) assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars) assertEquals(listOf('a', 'b', 'c'), chars)
} }
test fun sorted() { @test fun sorted() {
sequenceOf(3, 7, 5).let { sequenceOf(3, 7, 5).let {
it.sorted().iterator().assertSorted { a, b -> a <= b } it.sorted().iterator().assertSorted { a, b -> a <= b }
it.sortedDescending().iterator().assertSorted { a, b -> a >= b } it.sortedDescending().iterator().assertSorted { a, b -> a >= b }
} }
} }
test fun sortedBy() { @test fun sortedBy() {
sequenceOf("it", "greater", "less").let { sequenceOf("it", "greater", "less").let {
it.sortedBy { it.length() }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length() } <= 0 } it.sortedBy { it.length() }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length() } <= 0 }
it.sortedByDescending { it.length() }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length() } >= 0 } it.sortedByDescending { it.length() }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length() } >= 0 }
@@ -332,7 +332,7 @@ public class SequenceTest {
} }
} }
test fun sortedWith() { @test fun sortedWith() {
val comparator = compareBy { s: String -> s.reversed() } val comparator = compareBy { s: String -> s.reversed() }
assertEquals(listOf("act", "wast", "test"), sequenceOf("act", "test", "wast").sortedWith(comparator).toList()) assertEquals(listOf("act", "wast", "test"), sequenceOf("act", "test", "wast").sortedWith(comparator).toList())
} }
@@ -4,29 +4,29 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class SetOperationsTest { class SetOperationsTest {
test fun distinct() { @test fun distinct() {
assertEquals(listOf(1, 3, 5), listOf(1, 3, 3, 1, 5, 1, 3).distinct()) assertEquals(listOf(1, 3, 5), listOf(1, 3, 3, 1, 5, 1, 3).distinct())
assertTrue(listOf<Int>().distinct().isEmpty()) assertTrue(listOf<Int>().distinct().isEmpty())
} }
test fun distinctBy() { @test fun distinctBy() {
assertEquals(listOf("some", "cat", "do"), arrayOf("some", "case", "cat", "do", "dog", "it").distinctBy { it.length() }) assertEquals(listOf("some", "cat", "do"), arrayOf("some", "case", "cat", "do", "dog", "it").distinctBy { it.length() })
assertTrue(charArrayOf().distinctBy { it }.isEmpty()) assertTrue(charArrayOf().distinctBy { it }.isEmpty())
} }
test fun union() { @test fun union() {
assertEquals(listOf(1, 3, 5), listOf(1, 3).union(listOf(5)).toList()) assertEquals(listOf(1, 3, 5), listOf(1, 3).union(listOf(5)).toList())
assertEquals(listOf(1), listOf<Int>().union(listOf(1)).toList()) assertEquals(listOf(1), listOf<Int>().union(listOf(1)).toList())
} }
test fun subtract() { @test fun subtract() {
assertEquals(listOf(1, 3), listOf(1, 3).subtract(listOf(5)).toList()) assertEquals(listOf(1, 3), listOf(1, 3).subtract(listOf(5)).toList())
assertEquals(listOf(1, 3), listOf(1, 3, 5).subtract(listOf(5)).toList()) assertEquals(listOf(1, 3), listOf(1, 3, 5).subtract(listOf(5)).toList())
assertTrue(listOf(1, 3, 5).subtract(listOf(1, 3, 5)).none()) assertTrue(listOf(1, 3, 5).subtract(listOf(1, 3, 5)).none())
assertTrue(listOf<Int>().subtract(listOf(1)).none()) assertTrue(listOf<Int>().subtract(listOf(1)).none())
} }
test fun intersect() { @test fun intersect() {
assertTrue(listOf(1, 3).intersect(listOf(5)).none()) assertTrue(listOf(1, 3).intersect(listOf(5)).none())
assertEquals(listOf(5), listOf(1, 3, 5).intersect(listOf(5)).toList()) assertEquals(listOf(5), listOf(1, 3, 5).intersect(listOf(5)).toList())
assertEquals(listOf(1, 3, 5), listOf(1, 3, 5).intersect(listOf(1, 3, 5)).toList()) assertEquals(listOf(1, 3, 5), listOf(1, 3, 5).intersect(listOf(1, 3, 5)).toList())
@@ -40,12 +40,12 @@ class SetOperationsTest {
assertEquals(setOf("foo", "bar", "cheese", "wine"), set2) assertEquals(setOf("foo", "bar", "cheese", "wine"), set2)
} }
test fun plusElement() = testPlus { it + "bar" + "cheese" + "wine" } @test fun plusElement() = testPlus { it + "bar" + "cheese" + "wine" }
test fun plusCollection() = testPlus { it + listOf("bar", "cheese", "wine") } @test fun plusCollection() = testPlus { it + listOf("bar", "cheese", "wine") }
test fun plusArray() = testPlus { it + arrayOf("bar", "cheese", "wine") } @test fun plusArray() = testPlus { it + arrayOf("bar", "cheese", "wine") }
test fun plusSequence() = testPlus { it + sequenceOf("bar", "cheese", "wine") } @test fun plusSequence() = testPlus { it + sequenceOf("bar", "cheese", "wine") }
test fun plusAssign() { @test fun plusAssign() {
// lets use a mutable variable // lets use a mutable variable
var set = setOf("a") var set = setOf("a")
val setOriginal = set val setOriginal = set
@@ -70,9 +70,9 @@ class SetOperationsTest {
assertEquals(setOf("foo"), b) assertEquals(setOf("foo"), b)
} }
test fun minusElement() = testMinus { it - "bar" - "zoo" } @test fun minusElement() = testMinus { it - "bar" - "zoo" }
test fun minusCollection() = testMinus { it - listOf("bar", "zoo") } @test fun minusCollection() = testMinus { it - listOf("bar", "zoo") }
test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") } @test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") }
test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") } @test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") }
} }
@@ -9,7 +9,7 @@ import java.util.concurrent.*
import java.util.concurrent.TimeUnit.* import java.util.concurrent.TimeUnit.*
class ThreadTest { class ThreadTest {
test fun scheduledTask() { @test fun scheduledTask() {
val pool = Executors.newFixedThreadPool(1) val pool = Executors.newFixedThreadPool(1)
val countDown = CountDownLatch(1) val countDown = CountDownLatch(1)
@@ -19,7 +19,7 @@ class ThreadTest {
assertTrue(countDown.await(2, SECONDS), "Count down is executed") assertTrue(countDown.await(2, SECONDS), "Count down is executed")
} }
test fun callableInvoke() { @test fun callableInvoke() {
val pool = Executors.newFixedThreadPool(1) val pool = Executors.newFixedThreadPool(1)
val future = pool.submit<String> { // type specification required here to choose overload for callable, see KT-7882 val future = pool.submit<String> { // type specification required here to choose overload for callable, see KT-7882
@@ -28,7 +28,7 @@ class ThreadTest {
assertEquals("Hello", future.get(2, SECONDS)) assertEquals("Hello", future.get(2, SECONDS))
} }
test fun threadLocalGetOrSet() { @test fun threadLocalGetOrSet() {
val v = ThreadLocal<String>() val v = ThreadLocal<String>()
assertEquals("v1", v.getOrSet { "v1" }) assertEquals("v1", v.getOrSet { "v1" })
@@ -9,7 +9,7 @@ import java.util.Timer
import org.junit.Test as test import org.junit.Test as test
class TimerTest { class TimerTest {
test fun scheduledTask() { @test fun scheduledTask() {
val counter = AtomicInteger(0) val counter = AtomicInteger(0)
val timer = Timer() val timer = Timer()
+1 -1
View File
@@ -7,7 +7,7 @@ import org.junit.Test as test
class DomBuilderTest() { class DomBuilderTest() {
test fun buildDocument() { @test fun buildDocument() {
var doc = createDocument() var doc = createDocument()
assertTrue { assertTrue {
+2 -2
View File
@@ -8,7 +8,7 @@ import org.junit.Test as test
class DomTest { class DomTest {
test fun testCreateDocument() { @test fun testCreateDocument() {
var doc = createDocument() var doc = createDocument()
assertNotNull(doc, "Should have created a document") assertNotNull(doc, "Should have created a document")
@@ -27,7 +27,7 @@ class DomTest {
println("document ${doc.toXmlString()}") println("document ${doc.toXmlString()}")
} }
test fun addText() { @test fun addText() {
var doc = createDocument() var doc = createDocument()
assertNotNull(doc, "Should have created a document") assertNotNull(doc, "Should have created a document")
+1 -1
View File
@@ -7,7 +7,7 @@ import org.junit.Test as test
class NextSiblingTest { class NextSiblingTest {
test fun nextSibling() { @test fun nextSibling() {
val doc = createDocument() val doc = createDocument()
doc.addElement("foo") { doc.addElement("foo") {
+42 -42
View File
@@ -14,13 +14,13 @@ import kotlin.test.assertTrue
class FilesTest { class FilesTest {
test fun testPath() { @test fun testPath() {
val fileSuf = System.currentTimeMillis().toString() val fileSuf = System.currentTimeMillis().toString()
val file1 = createTempFile("temp", fileSuf) val file1 = createTempFile("temp", fileSuf)
assertTrue(file1.path.endsWith(fileSuf), file1.path) assertTrue(file1.path.endsWith(fileSuf), file1.path)
} }
test fun testCreateTempDir() { @test fun testCreateTempDir() {
val dirSuf = System.currentTimeMillis().toString() val dirSuf = System.currentTimeMillis().toString()
val dir1 = createTempDir("temp", dirSuf) val dir1 = createTempDir("temp", dirSuf)
assert(dir1.exists() && dir1.isDirectory() && dir1.name.startsWith("temp") && dir1.name.endsWith(dirSuf)) assert(dir1.exists() && dir1.isDirectory() && dir1.name.startsWith("temp") && dir1.name.endsWith(dirSuf))
@@ -41,7 +41,7 @@ class FilesTest {
dir3.delete() dir3.delete()
} }
test fun testCreateTempFile() { @test fun testCreateTempFile() {
val fileSuf = System.currentTimeMillis().toString() val fileSuf = System.currentTimeMillis().toString()
val file1 = createTempFile("temp", fileSuf) val file1 = createTempFile("temp", fileSuf)
assert(file1.exists() && file1.name.startsWith("temp") && file1.name.endsWith(fileSuf)) assert(file1.exists() && file1.name.startsWith("temp") && file1.name.endsWith(fileSuf))
@@ -79,7 +79,7 @@ class FilesTest {
} }
} }
test fun withSimple() { @test fun withSimple() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val referenceNames = val referenceNames =
@@ -104,7 +104,7 @@ class FilesTest {
} }
} }
test fun withEnterLeave() { @test fun withEnterLeave() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val referenceNames = val referenceNames =
@@ -163,7 +163,7 @@ class FilesTest {
} }
} }
test fun withFilterAndMap() { @test fun withFilterAndMap() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val referenceNames = val referenceNames =
@@ -178,7 +178,7 @@ class FilesTest {
} }
test fun withDeleteTxtTopDown() { @test fun withDeleteTxtTopDown() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val referenceNames = val referenceNames =
@@ -203,7 +203,7 @@ class FilesTest {
} }
} }
test fun withDeleteTxtBottomUp() { @test fun withDeleteTxtBottomUp() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val referenceNames = val referenceNames =
@@ -228,7 +228,7 @@ class FilesTest {
} }
} }
test fun withFilter() { @test fun withFilter() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
fun filter(file: File): Boolean { fun filter(file: File): Boolean {
@@ -258,7 +258,7 @@ class FilesTest {
} }
} }
test fun withTotalFilter() { @test fun withTotalFilter() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val referenceNames: Set<String> = setOf() val referenceNames: Set<String> = setOf()
@@ -283,7 +283,7 @@ class FilesTest {
} }
} }
test fun withForEach() { @test fun withForEach() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
var i = 0 var i = 0
@@ -297,7 +297,7 @@ class FilesTest {
} }
} }
test fun withCount() { @test fun withCount() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
assertEquals(10, basedir.walkTopDown().count()); assertEquals(10, basedir.walkTopDown().count());
@@ -307,7 +307,7 @@ class FilesTest {
} }
} }
test fun withReduce() { @test fun withReduce() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val res = basedir.walkTopDown().reduce { a, b -> if (a.canonicalPath > b.canonicalPath) a else b } val res = basedir.walkTopDown().reduce { a, b -> if (a.canonicalPath > b.canonicalPath) a else b }
@@ -317,7 +317,7 @@ class FilesTest {
} }
} }
test fun withVisitorAndDepth() { @test fun withVisitorAndDepth() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val files = HashSet<String>() val files = HashSet<String>()
@@ -394,7 +394,7 @@ class FilesTest {
} }
} }
test fun topDown() { @test fun topDown() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
val visited = HashSet<File>() val visited = HashSet<File>()
@@ -411,7 +411,7 @@ class FilesTest {
} }
} }
test fun restrictedAccess() { @test fun restrictedAccess() {
val basedir = createTestFiles() val basedir = createTestFiles()
val restricted = File(basedir, "1") val restricted = File(basedir, "1")
try { try {
@@ -431,7 +431,7 @@ class FilesTest {
} }
} }
test fun backup() { @test fun backup() {
var count = 0 var count = 0
fun makeBackup(file: File) { fun makeBackup(file: File) {
count++ count++
@@ -465,7 +465,7 @@ class FilesTest {
} }
} }
test fun find() { @test fun find() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
File(basedir, "8/4.txt".separatorsToSystem()).createNewFile() File(basedir, "8/4.txt".separatorsToSystem()).createNewFile()
@@ -481,7 +481,7 @@ class FilesTest {
} }
} }
test fun findGits() { @test fun findGits() {
val basedir = createTestFiles() val basedir = createTestFiles()
try { try {
File(basedir, "1/3/.git").mkdir() File(basedir, "1/3/.git").mkdir()
@@ -499,7 +499,7 @@ class FilesTest {
} }
} }
test fun streamFileTree() { @test fun streamFileTree() {
val dir = createTempDir() val dir = createTempDir()
try { try {
val subDir1 = createTempDir(prefix = "d1_", directory = dir) val subDir1 = createTempDir(prefix = "d1_", directory = dir)
@@ -523,7 +523,7 @@ class FilesTest {
} }
} }
test fun recurse() { @test fun recurse() {
val set: MutableSet<String> = HashSet() val set: MutableSet<String> = HashSet()
val dir = createTestFiles() val dir = createTestFiles()
dir.recurse { set.add(it.path) } dir.recurse { set.add(it.path) }
@@ -531,7 +531,7 @@ class FilesTest {
} }
} }
test fun listFilesWithFilter() { @test fun listFilesWithFilter() {
val dir = createTempDir("temp") val dir = createTempDir("temp")
createTempFile("temp1", ".kt", dir) createTempFile("temp1", ".kt", dir)
@@ -546,7 +546,7 @@ class FilesTest {
assertEquals(2, result2!!.size()) assertEquals(2, result2!!.size())
} }
test fun relativeToTest() { @test fun relativeToTest() {
val file1 = File("/foo/bar/baz") val file1 = File("/foo/bar/baz")
val file2 = File("/foo/baa/ghoo") val file2 = File("/foo/baa/ghoo")
assertEquals("../../bar/baz".separatorsToSystem(), file1.relativeTo(file2)) assertEquals("../../bar/baz".separatorsToSystem(), file1.relativeTo(file2))
@@ -577,7 +577,7 @@ class FilesTest {
assertEquals("..", file11.relativeTo(file10)) assertEquals("..", file11.relativeTo(file10))
} }
test fun relativeTo() { @test fun relativeTo() {
assertEquals("kotlin", File("src/kotlin".separatorsToSystem()).relativeTo(File("src"))) assertEquals("kotlin", File("src/kotlin".separatorsToSystem()).relativeTo(File("src")))
assertEquals("", File("dir").relativeTo(File("dir"))) assertEquals("", File("dir").relativeTo(File("dir")))
assertEquals("..", File("dir").relativeTo(File("dir/subdir".separatorsToSystem()))) assertEquals("..", File("dir").relativeTo(File("dir/subdir".separatorsToSystem())))
@@ -596,7 +596,7 @@ class FilesTest {
} }
} }
test fun relativePath() { @test fun relativePath() {
val file1 = File("src") val file1 = File("src")
val file2 = File(file1, "kotlin") val file2 = File(file1, "kotlin")
val file3 = File("test") val file3 = File("test")
@@ -616,7 +616,7 @@ class FilesTest {
assertEquals(elements.size(), i) assertEquals(elements.size(), i)
} }
test fun fileIterator() { @test fun fileIterator() {
checkFileElements(File("/foo/bar"), File("/"), listOf("foo", "bar")) checkFileElements(File("/foo/bar"), File("/"), listOf("foo", "bar"))
checkFileElements(File("\\foo\\bar"), File("\\".separatorsToSystem()), listOf("foo", "bar")) checkFileElements(File("\\foo\\bar"), File("\\".separatorsToSystem()), listOf("foo", "bar"))
checkFileElements(File("/foo/bar/gav"), File("/"), listOf("foo", "bar", "gav")) checkFileElements(File("/foo/bar/gav"), File("/"), listOf("foo", "bar", "gav"))
@@ -637,13 +637,13 @@ class FilesTest {
checkFileElements(File(".."), null, listOf("..")) checkFileElements(File(".."), null, listOf(".."))
} }
test fun startsWith() { @test fun startsWith() {
assertTrue(File("C:\\Users\\Me\\Temp\\Game").startsWith("C:\\Users\\Me")) assertTrue(File("C:\\Users\\Me\\Temp\\Game").startsWith("C:\\Users\\Me"))
assertFalse(File("C:\\Users\\Me\\Temp\\Game").startsWith("C:\\Users\\He")) assertFalse(File("C:\\Users\\Me\\Temp\\Game").startsWith("C:\\Users\\He"))
assertTrue(File("C:\\Users\\Me").startsWith("C:\\")) assertTrue(File("C:\\Users\\Me").startsWith("C:\\"))
} }
test fun endsWith() { @test fun endsWith() {
assertTrue(File("/foo/bar").endsWith("bar")) assertTrue(File("/foo/bar").endsWith("bar"))
assertTrue(File("/foo/bar").endsWith("/bar")) assertTrue(File("/foo/bar").endsWith("/bar"))
assertTrue(File("/foo/bar/gav/bar").endsWith("/bar")) assertTrue(File("/foo/bar/gav/bar").endsWith("/bar"))
@@ -652,7 +652,7 @@ class FilesTest {
assertFalse(File("foo/bar").endsWith("/bar")) assertFalse(File("foo/bar").endsWith("/bar"))
} }
test fun subPath() { @test fun subPath() {
if (File.separatorChar == '\\') { if (File.separatorChar == '\\') {
// Check only in Windows // Check only in Windows
assertEquals(File("mike"), File("//my.host.net/home/mike/temp").subPath(0, 1)) assertEquals(File("mike"), File("//my.host.net/home/mike/temp").subPath(0, 1))
@@ -663,7 +663,7 @@ class FilesTest {
assertEquals(File("gav/hi"), File("/foo/bar/gav/hi").subPath(2, 4)) assertEquals(File("gav/hi"), File("/foo/bar/gav/hi").subPath(2, 4))
} }
test fun normalize() { @test fun normalize() {
assertEquals(File("/foo/bar/baaz"), File("/foo/./bar/gav/../baaz").normalize()) assertEquals(File("/foo/bar/baaz"), File("/foo/./bar/gav/../baaz").normalize())
assertEquals(File("/foo/bar/baaz"), File("/foo/bak/../bar/gav/../baaz").normalize()) assertEquals(File("/foo/bar/baaz"), File("/foo/bak/../bar/gav/../baaz").normalize())
assertEquals(File("../../bar"), File("../foo/../../bar").normalize()) assertEquals(File("../../bar"), File("../foo/../../bar").normalize())
@@ -674,7 +674,7 @@ class FilesTest {
assertEquals(File("foo"), File("gav/bar/../../foo").normalize()) assertEquals(File("foo"), File("gav/bar/../../foo").normalize())
} }
test fun resolve() { @test fun resolve() {
assertEquals(File("/foo/bar/gav"), File("/foo/bar").resolve("gav")) assertEquals(File("/foo/bar/gav"), File("/foo/bar").resolve("gav"))
assertEquals(File("/foo/bar/gav"), File("/foo/bar/").resolve("gav")) assertEquals(File("/foo/bar/gav"), File("/foo/bar/").resolve("gav"))
assertEquals(File("/gav"), File("/foo/bar").resolve("/gav")) assertEquals(File("/gav"), File("/foo/bar").resolve("/gav"))
@@ -685,7 +685,7 @@ class FilesTest {
File("C:/Users/Me").resolve("Documents/important.doc")) File("C:/Users/Me").resolve("Documents/important.doc"))
} }
test fun resolveSibling() { @test fun resolveSibling() {
assertEquals(File("/foo/gav"), File("/foo/bar").resolveSibling("gav")) assertEquals(File("/foo/gav"), File("/foo/bar").resolveSibling("gav"))
assertEquals(File("/foo/gav"), File("/foo/bar/").resolveSibling("gav")) assertEquals(File("/foo/gav"), File("/foo/bar/").resolveSibling("gav"))
assertEquals(File("/gav"), File("/foo/bar").resolveSibling("/gav")) assertEquals(File("/gav"), File("/foo/bar").resolveSibling("/gav"))
@@ -696,7 +696,7 @@ class FilesTest {
File("C:/Users/Me/profile.ini").resolveSibling("Documents/important.doc")) File("C:/Users/Me/profile.ini").resolveSibling("Documents/important.doc"))
} }
test fun extension() { @test fun extension() {
assertEquals("bbb", File("aaa.bbb").extension) assertEquals("bbb", File("aaa.bbb").extension)
assertEquals("", File("aaa").extension) assertEquals("", File("aaa").extension)
assertEquals("", File("aaa.").extension) assertEquals("", File("aaa.").extension)
@@ -705,7 +705,7 @@ class FilesTest {
assertEquals("", File("/my.dir/log").extension) assertEquals("", File("/my.dir/log").extension)
} }
test fun nameWithoutExtension() { @test fun nameWithoutExtension() {
assertEquals("aaa", File("aaa.bbb").nameWithoutExtension) assertEquals("aaa", File("aaa.bbb").nameWithoutExtension)
assertEquals("aaa", File("aaa").nameWithoutExtension) assertEquals("aaa", File("aaa").nameWithoutExtension)
assertEquals("aaa", File("aaa.").nameWithoutExtension) assertEquals("aaa", File("aaa.").nameWithoutExtension)
@@ -713,7 +713,7 @@ class FilesTest {
assertEquals("log", File("/my.dir/log").nameWithoutExtension) assertEquals("log", File("/my.dir/log").nameWithoutExtension)
} }
test fun separatorsToSystem() { @test fun separatorsToSystem() {
var path = "/aaa/bbb/ccc" var path = "/aaa/bbb/ccc"
assertEquals(path.replace("/", File.separator), File(path).separatorsToSystem()) assertEquals(path.replace("/", File.separator), File(path).separatorsToSystem())
@@ -733,7 +733,7 @@ class FilesTest {
assertEquals("test", "test".allSeparatorsToSystem()) assertEquals("test", "test".allSeparatorsToSystem())
} }
test fun testCopyTo() { @test fun testCopyTo() {
val srcFile = createTempFile() val srcFile = createTempFile()
val dstFile = createTempFile() val dstFile = createTempFile()
srcFile.writeText("Hello, World!", "UTF8") srcFile.writeText("Hello, World!", "UTF8")
@@ -780,7 +780,7 @@ class FilesTest {
srcFile.delete() srcFile.delete()
} }
test fun copyToNameWithoutParent() { @test fun copyToNameWithoutParent() {
val currentDir = File("").getAbsoluteFile()!! val currentDir = File("").getAbsoluteFile()!!
val srcFile = createTempFile() val srcFile = createTempFile()
val dstFile = createTempFile(directory = currentDir) val dstFile = createTempFile(directory = currentDir)
@@ -800,7 +800,7 @@ class FilesTest {
} }
} }
test fun deleteRecursively() { @test fun deleteRecursively() {
val dir = createTempDir() val dir = createTempDir()
dir.delete() dir.delete()
dir.mkdir() dir.mkdir()
@@ -814,7 +814,7 @@ class FilesTest {
assert(!dir.deleteRecursively()) assert(!dir.deleteRecursively())
} }
test fun deleteRecursivelyWithFail() { @test fun deleteRecursivelyWithFail() {
val basedir = Walks.createTestFiles() val basedir = Walks.createTestFiles()
val restricted = File(basedir, "1") val restricted = File(basedir, "1")
try { try {
@@ -837,7 +837,7 @@ class FilesTest {
} }
} }
test fun copyRecursively() { @test fun copyRecursively() {
val src = createTempDir() val src = createTempDir()
val dst = createTempDir() val dst = createTempDir()
dst.delete() dst.delete()
@@ -921,7 +921,7 @@ class FilesTest {
} }
} }
test fun helpers1() { @test fun helpers1() {
val str = "123456789\n" val str = "123456789\n"
System.setIn(str.byteInputStream()) System.setIn(str.byteInputStream())
val reader = System.`in`.bufferedReader() val reader = System.`in`.bufferedReader()
@@ -932,7 +932,7 @@ class FilesTest {
assertEquals('3', stringReader.read().toChar()) assertEquals('3', stringReader.read().toChar())
} }
test fun helpers2() { @test fun helpers2() {
val file = createTempFile() val file = createTempFile()
val writer = file.printWriter() val writer = file.printWriter()
val str1 = "Hello, world!" val str1 = "Hello, world!"
+1 -1
View File
@@ -7,7 +7,7 @@ import java.io.BufferedReader
import java.io.File import java.io.File
class IOStreamsTest { class IOStreamsTest {
test fun testGetStreamOfFile() { @test fun testGetStreamOfFile() {
val tmpFile = createTempFile() val tmpFile = createTempFile()
var writer: Writer? = null var writer: Writer? = null
try { try {
+8 -8
View File
@@ -13,7 +13,7 @@ import kotlin.test.assertTrue
fun sample(): Reader = StringReader("Hello\nWorld"); fun sample(): Reader = StringReader("Hello\nWorld");
class ReadWriteTest { class ReadWriteTest {
test fun testAppendText() { @test fun testAppendText() {
val file = File.createTempFile("temp", System.nanoTime().toString()) val file = File.createTempFile("temp", System.nanoTime().toString())
file.writeText("Hello\n", "UTF8") file.writeText("Hello\n", "UTF8")
file.appendText("World\n", "UTF8") file.appendText("World\n", "UTF8")
@@ -24,7 +24,7 @@ class ReadWriteTest {
file.deleteOnExit() file.deleteOnExit()
} }
test fun reader() { @test fun reader() {
val list = ArrayList<String>() val list = ArrayList<String>()
/* TODO would be nicer maybe to write this as /* TODO would be nicer maybe to write this as
@@ -63,7 +63,7 @@ class ReadWriteTest {
assertEquals(2, c) assertEquals(2, c)
} }
test fun file() { @test fun file() {
val file = File.createTempFile("temp", System.nanoTime().toString()) val file = File.createTempFile("temp", System.nanoTime().toString())
val writer = file.outputStream().writer().buffered() val writer = file.outputStream().writer().buffered()
@@ -109,7 +109,7 @@ class ReadWriteTest {
} }
class LineIteratorTest { class LineIteratorTest {
test fun useLines() { @test fun useLines() {
// TODO we should maybe zap the useLines approach as it encourages // TODO we should maybe zap the useLines approach as it encourages
// use of iterators which don't close the underlying stream // use of iterators which don't close the underlying stream
val list1 = sample().useLines { it.toArrayList() } val list1 = sample().useLines { it.toArrayList() }
@@ -119,7 +119,7 @@ class ReadWriteTest {
assertEquals(arrayListOf("Hello", "World"), list2) assertEquals(arrayListOf("Hello", "World"), list2)
} }
test fun manualClose() { @test fun manualClose() {
val reader = sample().buffered() val reader = sample().buffered()
try { try {
val list = reader.lineSequence().toArrayList() val list = reader.lineSequence().toArrayList()
@@ -129,7 +129,7 @@ class ReadWriteTest {
} }
} }
test fun boundaryConditions() { @test fun boundaryConditions() {
var reader = StringReader("").buffered() var reader = StringReader("").buffered()
assertEquals(ArrayList<String>(), reader.lineSequence().toArrayList()) assertEquals(ArrayList<String>(), reader.lineSequence().toArrayList())
reader.close() reader.close()
@@ -148,7 +148,7 @@ class ReadWriteTest {
} }
} }
test fun testUse() { @test fun testUse() {
val list = ArrayList<String>() val list = ArrayList<String>()
val reader = sample().buffered() val reader = sample().buffered()
@@ -165,7 +165,7 @@ class ReadWriteTest {
assertEquals(arrayListOf("Hello", "World"), list) assertEquals(arrayListOf("Hello", "World"), list)
} }
test fun testURL() { @test fun testURL() {
val url = URL("http://kotlinlang.org") val url = URL("http://kotlinlang.org")
val text = url.readText() val text = url.readText()
assertFalse(text.isEmpty()) assertFalse(text.isEmpty())
@@ -7,7 +7,8 @@ import org.junit.Test
class FunctionIteratorTest { class FunctionIteratorTest {
Test fun iterateOverFunction() { @Test
fun iterateOverFunction() {
var count = 3 var count = 3
val iter = sequence<Int> { val iter = sequence<Int> {
@@ -19,7 +20,8 @@ class FunctionIteratorTest {
assertEquals(arrayListOf(2, 1, 0), list) assertEquals(arrayListOf(2, 1, 0), list)
} }
Test fun iterateOverFunction2() { @Test
fun iterateOverFunction2() {
val values = sequence<Int>(3) { n -> if (n > 0) n - 1 else null } val values = sequence<Int>(3) { n -> if (n > 0) n - 1 else null }
assertEquals(arrayListOf(3, 2, 1, 0), values.toList()) assertEquals(arrayListOf(3, 2, 1, 0), values.toList())
} }
@@ -6,7 +6,7 @@ import org.junit.Test as test
class IteratorsJVMTest { class IteratorsJVMTest {
test fun flatMapAndTakeExtractTheTransformedElements() { @test fun flatMapAndTakeExtractTheTransformedElements() {
fun intToBinaryDigits() = { i: Int -> fun intToBinaryDigits() = { i: Int ->
val binary = Integer.toBinaryString(i)!! val binary = Integer.toBinaryString(i)!!
var index = 0 var index = 0
@@ -25,7 +25,7 @@ class IteratorsJVMTest {
assertEquals(expected, fibonacci().flatMap<Int, Char>(intToBinaryDigits()).take(10).toList()) assertEquals(expected, fibonacci().flatMap<Int, Char>(intToBinaryDigits()).take(10).toList())
} }
test fun flatMapOnIterator() { @test fun flatMapOnIterator() {
val result = sequenceOf(1, 2).flatMap { i -> (0..i).asSequence()} val result = sequenceOf(1, 2).flatMap { i -> (0..i).asSequence()}
assertEquals(listOf(0, 1, 0, 1, 2), result.toList()) assertEquals(listOf(0, 1, 0, 1, 2), result.toList())
} }
@@ -13,32 +13,32 @@ fun fibonacci(): Sequence<Int> {
class IteratorsTest { class IteratorsTest {
test fun filterAndTakeWhileExtractTheElementsWithinRange() { @test fun filterAndTakeWhileExtractTheElementsWithinRange() {
assertEquals(arrayListOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList()) assertEquals(arrayListOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList())
} }
test fun foldReducesTheFirstNElements() { @test fun foldReducesTheFirstNElements() {
val sum = { a: Int, b: Int -> a + b } val sum = { a: Int, b: Int -> a + b }
assertEquals(arrayListOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum)) assertEquals(arrayListOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum))
} }
test fun takeExtractsTheFirstNElements() { @test fun takeExtractsTheFirstNElements() {
assertEquals(arrayListOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList()) assertEquals(arrayListOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList())
} }
test fun mapAndTakeWhileExtractTheTransformedElements() { @test fun mapAndTakeWhileExtractTheTransformedElements() {
assertEquals(arrayListOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList()) assertEquals(arrayListOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList())
} }
test fun mapIndexed() { @test fun mapIndexed() {
assertEquals(arrayListOf(0, 1, 2, 6, 12), fibonacci().mapIndexed { index, value -> index * value }.takeWhile { i: Int -> i < 20 }.toList()) assertEquals(arrayListOf(0, 1, 2, 6, 12), fibonacci().mapIndexed { index, value -> index * value }.takeWhile { i: Int -> i < 20 }.toList())
} }
test fun joinConcatenatesTheFirstNElementsAboveAThreshold() { @test fun joinConcatenatesTheFirstNElementsAboveAThreshold() {
assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.joinToString(separator = ", ", limit = 5)) assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.joinToString(separator = ", ", limit = 5))
} }
test fun plus() { @test fun plus() {
val iter = arrayListOf("foo", "bar").asSequence() val iter = arrayListOf("foo", "bar").asSequence()
val iter2 = iter + "cheese" val iter2 = iter + "cheese"
assertEquals(arrayListOf("foo", "bar", "cheese"), iter2.toList()) assertEquals(arrayListOf("foo", "bar", "cheese"), iter2.toList())
@@ -49,7 +49,7 @@ class IteratorsTest {
assertEquals(arrayListOf("a", "b", "c"), mi.toList()) assertEquals(arrayListOf("a", "b", "c"), mi.toList())
} }
test fun plusCollection() { @test fun plusCollection() {
val a = arrayListOf("foo", "bar") val a = arrayListOf("foo", "bar")
val b = arrayListOf("cheese", "wine") val b = arrayListOf("cheese", "wine")
val iter = a.asSequence() + b.asSequence() val iter = a.asSequence() + b.asSequence()
@@ -64,7 +64,7 @@ class IteratorsTest {
assertEquals(arrayListOf("a", "foo", "bar", "beer", "cheese", "wine", "z"), ml.toList()) assertEquals(arrayListOf("a", "foo", "bar", "beer", "cheese", "wine", "z"), ml.toList())
} }
test fun requireNoNulls() { @test fun requireNoNulls() {
val iter = arrayListOf<String?>("foo", "bar").asSequence() val iter = arrayListOf<String?>("foo", "bar").asSequence()
val notNull = iter.requireNoNulls() val notNull = iter.requireNoNulls()
assertEquals(arrayListOf("foo", "bar"), notNull.toList()) assertEquals(arrayListOf("foo", "bar"), notNull.toList())
@@ -77,23 +77,23 @@ class IteratorsTest {
} }
} }
test fun toStringJoinsNoMoreThanTheFirstTenElements() { @test fun toStringJoinsNoMoreThanTheFirstTenElements() {
assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().joinToString(limit = 10)) assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().joinToString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.joinToString(limit = 10))
assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.joinToString()) assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.joinToString())
} }
test fun pairIterator() { @test fun pairIterator() {
val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).joinToString(limit = 10) val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).joinToString(limit = 10)
assertEquals("(0, 0), (1, 2), (1, 2), (2, 4), (3, 6), (5, 10), (8, 16), (13, 26), (21, 42), (34, 68), ...", pairStr) assertEquals("(0, 0), (1, 2), (1, 2), (2, 4), (3, 6), (5, 10), (8, 16), (13, 26), (21, 42), (34, 68), ...", pairStr)
} }
test fun skippingIterator() { @test fun skippingIterator() {
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).joinToString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(3).drop(4).joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(3).drop(4).joinToString(limit = 10))
} }
test fun iterationOverIterator() { @test fun iterationOverIterator() {
val c = arrayListOf(0, 1, 2, 3, 4, 5) val c = arrayListOf(0, 1, 2, 3, 4, 5)
var s = "" var s = ""
for (i in c.iterator()) { for (i in c.iterator()) {
@@ -107,7 +107,7 @@ class IteratorsTest {
return result return result
} }
test fun iterableExtension() { @test fun iterableExtension() {
val c = arrayListOf(0, 1, 2, 3, 4, 5) val c = arrayListOf(0, 1, 2, 3, 4, 5)
val d = ArrayList<Int>() val d = ArrayList<Int>()
c.iterator().takeWhileTo(d, {i -> i < 4 }) c.iterator().takeWhileTo(d, {i -> i < 4 })
+2 -2
View File
@@ -6,7 +6,7 @@ import java.util.ArrayList;
class JsArrayTest { class JsArrayTest {
test fun arraySizeAndToList() { @test fun arraySizeAndToList() {
val a1 = arrayOf<String>() val a1 = arrayOf<String>()
val a2 = arrayOf("foo") val a2 = arrayOf("foo")
val a3 = arrayOf("foo", "bar") val a3 = arrayOf("foo", "bar")
@@ -21,7 +21,7 @@ class JsArrayTest {
} }
test fun arrayListFromCollection() { @test fun arrayListFromCollection() {
var c: Collection<String> = arrayOf("A", "B", "C").toList() var c: Collection<String> = arrayOf("A", "B", "C").toList()
var a = ArrayList(c) var a = ArrayList(c)
+12 -12
View File
@@ -9,7 +9,7 @@ import org.junit.Test as test
class JsDomTest { class JsDomTest {
test fun testCreateDocument() { @test fun testCreateDocument() {
var doc = document var doc = document
assertNotNull(doc, "Should have created a document") assertNotNull(doc, "Should have created a document")
@@ -25,7 +25,7 @@ class JsDomTest {
assertCssClass(e, "bar") assertCssClass(e, "bar")
} }
test fun addText() { @test fun addText() {
var doc = document var doc = document
assertNotNull(doc, "Should have created a document") assertNotNull(doc, "Should have created a document")
@@ -38,7 +38,7 @@ class JsDomTest {
assertEquals("hello", e.textContent) assertEquals("hello", e.textContent)
} }
test fun testAddClassMissing() { @test fun testAddClassMissing() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
assertNotNull(e) assertNotNull(e)
@@ -49,7 +49,7 @@ class JsDomTest {
assertEquals("class1 class2", e.classes) assertEquals("class1 class2", e.classes)
} }
test fun testAddClassPresent() { @test fun testAddClassPresent() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
assertNotNull(e) assertNotNull(e)
@@ -60,13 +60,13 @@ class JsDomTest {
assertEquals("class2 class1", e.classes) assertEquals("class2 class1", e.classes)
} }
test fun testAddClassUndefinedClasses() { @test fun testAddClassUndefinedClasses() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
e.addClass("class1") e.addClass("class1")
assertEquals("class1", e.classes) assertEquals("class1", e.classes)
} }
test fun testRemoveClassMissing() { @test fun testRemoveClassMissing() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
assertNotNull(e) assertNotNull(e)
@@ -77,7 +77,7 @@ class JsDomTest {
assertEquals("class2 class1", e.classes) assertEquals("class2 class1", e.classes)
} }
test fun testRemoveClassPresent1() { @test fun testRemoveClassPresent1() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
assertNotNull(e) assertNotNull(e)
@@ -88,7 +88,7 @@ class JsDomTest {
assertEquals("class1", e.classes) assertEquals("class1", e.classes)
} }
test fun testRemoveClassPresent2() { @test fun testRemoveClassPresent2() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
assertNotNull(e) assertNotNull(e)
@@ -99,7 +99,7 @@ class JsDomTest {
assertEquals("class2", e.classes) assertEquals("class2", e.classes)
} }
test fun testRemoveClassPresent3() { @test fun testRemoveClassPresent3() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
assertNotNull(e) assertNotNull(e)
@@ -110,13 +110,13 @@ class JsDomTest {
assertEquals("class2 class3", e.classes) assertEquals("class2 class3", e.classes)
} }
test fun testRemoveClassUndefinedClasses() { @test fun testRemoveClassUndefinedClasses() {
val e = document.createElement("e")!! val e = document.createElement("e")!!
e.removeClass("class1") e.removeClass("class1")
assertEquals("", e.classes) assertEquals("", e.classes)
} }
test fun testRemoveFromParent() { @test fun testRemoveFromParent() {
val doc = document val doc = document
val parent = doc.createElement("pp") val parent = doc.createElement("pp")
@@ -135,7 +135,7 @@ class JsDomTest {
assertNull(child.parentNode) assertNull(child.parentNode)
} }
test fun testRemoveFromParentOrphanNode() { @test fun testRemoveFromParentOrphanNode() {
val child = document.createElement("cc") val child = document.createElement("cc")
child.removeFromParent() child.removeFromParent()
+31 -31
View File
@@ -17,7 +17,7 @@ class ComplexMapJsTest : MapJsTest() {
assertEquals(KEYS.toNormalizedList(), map.keySet().toNormalizedList()) assertEquals(KEYS.toNormalizedList(), map.keySet().toNormalizedList())
assertEquals(VALUES.toNormalizedList(), map.values().toNormalizedList()) assertEquals(VALUES.toNormalizedList(), map.values().toNormalizedList())
} }
test override fun constructors() { @test override fun constructors() {
doTest<String>() doTest<String>()
} }
@@ -28,7 +28,7 @@ class ComplexMapJsTest : MapJsTest() {
} }
class PrimitiveMapJsTest : MapJsTest() { class PrimitiveMapJsTest : MapJsTest() {
test override fun constructors() { @test override fun constructors() {
HashMap<String, Int>() HashMap<String, Int>()
HashMap<String, Int>(3) HashMap<String, Int>(3)
HashMap<String, Int>(3, 0.5f) HashMap<String, Int>(3, 0.5f)
@@ -43,7 +43,7 @@ class PrimitiveMapJsTest : MapJsTest() {
override fun emptyMutableMap(): MutableMap<String, Int> = HashMap() override fun emptyMutableMap(): MutableMap<String, Int> = HashMap()
override fun emptyMutableMapWithNullableKeyValue(): MutableMap<String?, Int?> = HashMap() override fun emptyMutableMapWithNullableKeyValue(): MutableMap<String?, Int?> = HashMap()
test fun compareBehavior() { @test fun compareBehavior() {
val specialJsStringMap = HashMap<String, Any>() val specialJsStringMap = HashMap<String, Any>()
specialJsStringMap.put("k1", "v1") specialJsStringMap.put("k1", "v1")
compare(genericHashMapOf("k1" to "v1"), specialJsStringMap) { mapBehavior() } compare(genericHashMapOf("k1" to "v1"), specialJsStringMap) { mapBehavior() }
@@ -55,7 +55,7 @@ class PrimitiveMapJsTest : MapJsTest() {
} }
class LinkedHashMapTest : MapJsTest() { class LinkedHashMapTest : MapJsTest() {
test override fun constructors() { @test override fun constructors() {
LinkedHashMap<String, Int>() LinkedHashMap<String, Int>()
LinkedHashMap<String, Int>(3) LinkedHashMap<String, Int>(3)
LinkedHashMap<String, Int>(3, 0.5f) LinkedHashMap<String, Int>(3, 0.5f)
@@ -77,7 +77,7 @@ abstract class MapJsTest {
val SPECIAL_NAMES = arrayOf("__proto__", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable") val SPECIAL_NAMES = arrayOf("__proto__", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable")
test fun getOrElse() { @test fun getOrElse() {
val data = emptyMap() val data = emptyMap()
val a = data.getOrElse("foo"){2} val a = data.getOrElse("foo"){2}
assertEquals(2, a) assertEquals(2, a)
@@ -87,7 +87,7 @@ abstract class MapJsTest {
assertEquals(0, data.size()) assertEquals(0, data.size())
} }
test fun getOrPut() { @test fun getOrPut() {
val data = emptyMutableMap() val data = emptyMutableMap()
val a = data.getOrPut("foo"){2} val a = data.getOrPut("foo"){2}
assertEquals(2, a) assertEquals(2, a)
@@ -98,13 +98,13 @@ abstract class MapJsTest {
assertEquals(1, data.size()) assertEquals(1, data.size())
} }
test fun emptyMapGet() { @test fun emptyMapGet() {
val map = emptyMap() val map = emptyMap()
assertEquals(null, map.get("foo"), """failed on map.get("foo")""") assertEquals(null, map.get("foo"), """failed on map.get("foo")""")
assertEquals(null, map["bar"], """failed on map["bar"]""") assertEquals(null, map["bar"], """failed on map["bar"]""")
} }
test fun mapGet() { @test fun mapGet() {
val map = createTestMap() val map = createTestMap()
for (i in KEYS.indices) { for (i in KEYS.indices) {
assertEquals(VALUES[i], map.get(KEYS[i]), """failed on map.get(KEYS[$i])""") assertEquals(VALUES[i], map.get(KEYS[i]), """failed on map.get(KEYS[$i])""")
@@ -114,7 +114,7 @@ abstract class MapJsTest {
assertEquals(null, map.get("foo")) assertEquals(null, map.get("foo"))
} }
test fun mapPut() { @test fun mapPut() {
val map = emptyMutableMap() val map = emptyMutableMap()
map.put("foo", 1) map.put("foo", 1)
@@ -130,7 +130,7 @@ abstract class MapJsTest {
assertEquals(2, map["bar"]) assertEquals(2, map["bar"])
} }
test fun sizeAndEmptyForEmptyMap() { @test fun sizeAndEmptyForEmptyMap() {
val data = emptyMap() val data = emptyMap()
assertTrue(data.isEmpty()) assertTrue(data.isEmpty())
@@ -140,7 +140,7 @@ abstract class MapJsTest {
assertEquals(0, data.size()) assertEquals(0, data.size())
} }
test fun sizeAndEmpty() { @test fun sizeAndEmpty() {
val data = createTestMap() val data = createTestMap()
assertFalse(data.isEmpty()) assertFalse(data.isEmpty())
@@ -150,22 +150,22 @@ abstract class MapJsTest {
} }
// #KT-3035 // #KT-3035
test fun emptyMapValues() { @test fun emptyMapValues() {
val emptyMap = emptyMap() val emptyMap = emptyMap()
assertTrue(emptyMap.values().isEmpty()) assertTrue(emptyMap.values().isEmpty())
} }
test fun mapValues() { @test fun mapValues() {
val map = createTestMap() val map = createTestMap()
assertEquals(VALUES.toNormalizedList(), map.values().toNormalizedList()) assertEquals(VALUES.toNormalizedList(), map.values().toNormalizedList())
} }
test fun mapKeySet() { @test fun mapKeySet() {
val map = createTestMap() val map = createTestMap()
assertEquals(KEYS.toNormalizedList(), map.keySet().toNormalizedList()) assertEquals(KEYS.toNormalizedList(), map.keySet().toNormalizedList())
} }
test fun mapEntrySet() { @test fun mapEntrySet() {
val map = createTestMap() val map = createTestMap()
val actualKeys = ArrayList<String>() val actualKeys = ArrayList<String>()
@@ -179,7 +179,7 @@ abstract class MapJsTest {
assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList())
} }
test fun mapContainsKey() { @test fun mapContainsKey() {
val map = createTestMap() val map = createTestMap()
assertTrue(map.containsKey(KEYS[0]) && assertTrue(map.containsKey(KEYS[0]) &&
@@ -191,7 +191,7 @@ abstract class MapJsTest {
map.containsKey(1)) map.containsKey(1))
} }
test fun mapContainsValue() { @test fun mapContainsValue() {
val map = createTestMap() val map = createTestMap()
assertTrue(map.containsValue(VALUES[0]) && assertTrue(map.containsValue(VALUES[0]) &&
@@ -203,14 +203,14 @@ abstract class MapJsTest {
map.containsValue(5)) map.containsValue(5))
} }
test fun mapPutAll() { @test fun mapPutAll() {
val map = createTestMap() val map = createTestMap()
val newMap = emptyMutableMap() val newMap = emptyMutableMap()
newMap.putAll(map) newMap.putAll(map)
assertEquals(KEYS.size(), newMap.size()) assertEquals(KEYS.size(), newMap.size())
} }
test fun mapRemove() { @test fun mapRemove() {
val map = createTestMutableMap() val map = createTestMutableMap()
val last = KEYS.size() - 1 val last = KEYS.size() - 1
val first = 0 val first = 0
@@ -227,14 +227,14 @@ abstract class MapJsTest {
assertEquals(KEYS.size() - 3, map.size()) assertEquals(KEYS.size() - 3, map.size())
} }
test fun mapClear() { @test fun mapClear() {
val map = createTestMutableMap() val map = createTestMutableMap()
assertFalse(map.isEmpty()) assertFalse(map.isEmpty())
map.clear() map.clear()
assertTrue(map.isEmpty()) assertTrue(map.isEmpty())
} }
test fun nullAsKey() { @test fun nullAsKey() {
val map = emptyMutableMapWithNullableKeyValue() val map = emptyMutableMapWithNullableKeyValue()
assertTrue(map.isEmpty()) assertTrue(map.isEmpty())
@@ -247,7 +247,7 @@ abstract class MapJsTest {
assertEquals(null, map[null]) assertEquals(null, map[null])
} }
test fun nullAsValue() { @test fun nullAsValue() {
val map = emptyMutableMapWithNullableKeyValue() val map = emptyMutableMapWithNullableKeyValue()
val KEY = "Key" val KEY = "Key"
@@ -260,7 +260,7 @@ abstract class MapJsTest {
assertTrue(map.isEmpty()) assertTrue(map.isEmpty())
} }
test fun setViaIndexOperators() { @test fun setViaIndexOperators() {
val map = HashMap<String, String>() val map = HashMap<String, String>()
assertTrue{ map.isEmpty() } assertTrue{ map.isEmpty() }
assertEquals(map.size(), 0) assertEquals(map.size(), 0)
@@ -272,21 +272,21 @@ abstract class MapJsTest {
assertEquals("James", map["name"]) assertEquals("James", map["name"])
} }
test fun createUsingPairs() { @test fun createUsingPairs() {
val map = mapOf(Pair("a", 1), Pair("b", 2)) val map = mapOf(Pair("a", 1), Pair("b", 2))
assertEquals(2, map.size()) assertEquals(2, map.size())
assertEquals(1, map.get("a")) assertEquals(1, map.get("a"))
assertEquals(2, map.get("b")) assertEquals(2, map.get("b"))
} }
test fun createUsingTo() { @test fun createUsingTo() {
val map = mapOf("a" to 1, "b" to 2) val map = mapOf("a" to 1, "b" to 2)
assertEquals(2, map.size()) assertEquals(2, map.size())
assertEquals(1, map.get("a")) assertEquals(1, map.get("a"))
assertEquals(2, map.get("b")) assertEquals(2, map.get("b"))
} }
test fun mapIteratorImplicitly() { @test fun mapIteratorImplicitly() {
val map = createTestMap() val map = createTestMap()
val actualKeys = ArrayList<String>() val actualKeys = ArrayList<String>()
@@ -300,7 +300,7 @@ abstract class MapJsTest {
assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList())
} }
test fun mapIteratorExplicitly() { @test fun mapIteratorExplicitly() {
val map = createTestMap() val map = createTestMap()
val actualKeys = ArrayList<String>() val actualKeys = ArrayList<String>()
@@ -315,7 +315,7 @@ abstract class MapJsTest {
assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList())
} }
test fun specialNamesNotContainsInEmptyMap() { @test fun specialNamesNotContainsInEmptyMap() {
val map = emptyMap() val map = emptyMap()
for (key in SPECIAL_NAMES) { for (key in SPECIAL_NAMES) {
@@ -323,7 +323,7 @@ abstract class MapJsTest {
} }
} }
test fun specialNamesNotContainsInNonEmptyMap() { @test fun specialNamesNotContainsInNonEmptyMap() {
val map = createTestMap() val map = createTestMap()
for (key in SPECIAL_NAMES) { for (key in SPECIAL_NAMES) {
@@ -331,7 +331,7 @@ abstract class MapJsTest {
} }
} }
test fun putAndGetSpecialNamesToMap() { @test fun putAndGetSpecialNamesToMap() {
val map = createTestMutableMap() val map = createTestMutableMap()
var value = 0 var value = 0
@@ -351,7 +351,7 @@ abstract class MapJsTest {
} }
} }
test abstract fun constructors() @test abstract fun constructors()
/* /*
test fun createLinkedMap() { test fun createLinkedMap() {
+40 -20
View File
@@ -18,7 +18,8 @@ class ComplexSetJsTest : SetJsTest() {
assertEquals(data, set) assertEquals(data, set)
} }
Test override fun constructors() { @Test
override fun constructors() {
doTest<String>() doTest<String>()
} }
@@ -32,7 +33,8 @@ class ComplexSetJsTest : SetJsTest() {
class PrimitiveSetJsTest : SetJsTest() { class PrimitiveSetJsTest : SetJsTest() {
override fun createEmptyMutableSet(): MutableSet<String> = HashSet() override fun createEmptyMutableSet(): MutableSet<String> = HashSet()
override fun createEmptyMutableSetWithNullableValues(): MutableSet<String?> = HashSet() override fun createEmptyMutableSetWithNullableValues(): MutableSet<String?> = HashSet()
Test override fun constructors() { @Test
override fun constructors() {
HashSet<String>() HashSet<String>()
HashSet<String>(3) HashSet<String>(3)
HashSet<String>(3, 0.5f) HashSet<String>(3, 0.5f)
@@ -42,7 +44,8 @@ class PrimitiveSetJsTest : SetJsTest() {
assertEquals(data, set) assertEquals(data, set)
} }
Test fun compareBehavior() { @Test
fun compareBehavior() {
val specialJsStringSet = HashSet<String>() val specialJsStringSet = HashSet<String>()
specialJsStringSet.add("kotlin") specialJsStringSet.add("kotlin")
compare(genericHashSetOf("kotlin"), specialJsStringSet) { setBehavior() } compare(genericHashSetOf("kotlin"), specialJsStringSet) { setBehavior() }
@@ -57,7 +60,8 @@ class PrimitiveSetJsTest : SetJsTest() {
class LinkedHashSetJsTest : SetJsTest() { class LinkedHashSetJsTest : SetJsTest() {
override fun createEmptyMutableSet(): MutableSet<String> = LinkedHashSet() override fun createEmptyMutableSet(): MutableSet<String> = LinkedHashSet()
override fun createEmptyMutableSetWithNullableValues(): MutableSet<String?> = LinkedHashSet() override fun createEmptyMutableSetWithNullableValues(): MutableSet<String?> = LinkedHashSet()
Test override fun constructors() { @Test
override fun constructors() {
LinkedHashSet<String>() LinkedHashSet<String>()
LinkedHashSet<String>(3) LinkedHashSet<String>(3)
LinkedHashSet<String>(3, 0.5f) LinkedHashSet<String>(3, 0.5f)
@@ -74,24 +78,28 @@ abstract class SetJsTest {
val SPECIAL_NAMES = arrayOf("__proto__", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable") val SPECIAL_NAMES = arrayOf("__proto__", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable")
Test fun size() { @Test
fun size() {
assertEquals(2, data.size()) assertEquals(2, data.size())
assertEquals(0, empty.size()) assertEquals(0, empty.size())
} }
Test fun isEmpty() { @Test
fun isEmpty() {
assertFalse(data.isEmpty()) assertFalse(data.isEmpty())
assertTrue(empty.isEmpty()) assertTrue(empty.isEmpty())
} }
Test fun equals() { @Test
fun equals() {
assertNotEquals(createEmptyMutableSet(), data) assertNotEquals(createEmptyMutableSet(), data)
assertNotEquals(data, empty) assertNotEquals(data, empty)
assertEquals(createEmptyMutableSet(), empty) assertEquals(createEmptyMutableSet(), empty)
assertEquals(createTestMutableSetReversed(), data) assertEquals(createTestMutableSetReversed(), data)
} }
Test fun contains() { @Test
fun contains() {
assertTrue(data.contains("foo")) assertTrue(data.contains("foo"))
assertTrue(data.contains("bar")) assertTrue(data.contains("bar"))
assertFalse(data.contains("baz")) assertFalse(data.contains("baz"))
@@ -102,7 +110,8 @@ abstract class SetJsTest {
assertFalse(empty.contains(1)) assertFalse(empty.contains(1))
} }
Test fun iterator() { @Test
fun iterator() {
var result = "" var result = ""
for (e in data) { for (e in data) {
result += e result += e
@@ -111,14 +120,16 @@ abstract class SetJsTest {
assertTrue(result == "foobar" || result == "barfoo") assertTrue(result == "foobar" || result == "barfoo")
} }
Test fun containsAll() { @Test
fun containsAll() {
assertTrue(data.containsAll(arrayListOf("foo", "bar"))) assertTrue(data.containsAll(arrayListOf("foo", "bar")))
assertTrue(data.containsAll(arrayListOf<String>())) assertTrue(data.containsAll(arrayListOf<String>()))
assertFalse(data.containsAll(arrayListOf("foo", "bar", "baz"))) assertFalse(data.containsAll(arrayListOf("foo", "bar", "baz")))
assertFalse(data.containsAll(arrayListOf("baz"))) assertFalse(data.containsAll(arrayListOf("baz")))
} }
Test fun add() { @Test
fun add() {
val data = createTestMutableSet() val data = createTestMutableSet()
assertTrue(data.add("baz")) assertTrue(data.add("baz"))
assertEquals(3, data.size()) assertEquals(3, data.size())
@@ -127,7 +138,8 @@ abstract class SetJsTest {
assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz"))) assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz")))
} }
Test fun remove() { @Test
fun remove() {
val data = createTestMutableSet() val data = createTestMutableSet()
assertTrue(data.remove("foo")) assertTrue(data.remove("foo"))
assertEquals(1, data.size()) assertEquals(1, data.size())
@@ -136,7 +148,8 @@ abstract class SetJsTest {
assertTrue(data.contains("bar")) assertTrue(data.contains("bar"))
} }
Test fun addAll() { @Test
fun addAll() {
val data = createTestMutableSet() val data = createTestMutableSet()
assertTrue(data.addAll(arrayListOf("foo", "bar", "baz", "boo"))) assertTrue(data.addAll(arrayListOf("foo", "bar", "baz", "boo")))
assertEquals(4, data.size()) assertEquals(4, data.size())
@@ -145,7 +158,8 @@ abstract class SetJsTest {
assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz", "boo"))) assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz", "boo")))
} }
Test fun removeAll() { @Test
fun removeAll() {
val data = createTestMutableSet() val data = createTestMutableSet()
assertFalse(data.removeAll(arrayListOf("baz"))) assertFalse(data.removeAll(arrayListOf("baz")))
assertTrue(data.containsAll(arrayListOf("foo", "bar"))) assertTrue(data.containsAll(arrayListOf("foo", "bar")))
@@ -161,7 +175,8 @@ abstract class SetJsTest {
assertTrue(data.isEmpty()) assertTrue(data.isEmpty())
} }
Test fun retainAll() { @Test
fun retainAll() {
val data1 = createTestMutableSet() val data1 = createTestMutableSet()
assertTrue(data1.retainAll(arrayListOf("baz"))) assertTrue(data1.retainAll(arrayListOf("baz")))
assertTrue(data1.isEmpty()) assertTrue(data1.isEmpty())
@@ -172,7 +187,8 @@ abstract class SetJsTest {
assertEquals(1, data2.size()) assertEquals(1, data2.size())
} }
Test fun clear() { @Test
fun clear() {
val data = createTestMutableSet() val data = createTestMutableSet()
data.clear() data.clear()
assertTrue(data.isEmpty()) assertTrue(data.isEmpty())
@@ -181,19 +197,22 @@ abstract class SetJsTest {
assertTrue(data.isEmpty()) assertTrue(data.isEmpty())
} }
Test fun specialNamesNotContainsInEmptySet() { @Test
fun specialNamesNotContainsInEmptySet() {
for (element in SPECIAL_NAMES) { for (element in SPECIAL_NAMES) {
assertFalse(empty.contains(element), "unexpected element: $element") assertFalse(empty.contains(element), "unexpected element: $element")
} }
} }
Test fun specialNamesNotContainsInNonEmptySet() { @Test
fun specialNamesNotContainsInNonEmptySet() {
for (element in SPECIAL_NAMES) { for (element in SPECIAL_NAMES) {
assertFalse(data.contains(element), "unexpected element: $element") assertFalse(data.contains(element), "unexpected element: $element")
} }
} }
Test fun putAndGetSpecialNamesToSet() { @Test
fun putAndGetSpecialNamesToSet() {
val s = createTestMutableSet() val s = createTestMutableSet()
for (element in SPECIAL_NAMES) { for (element in SPECIAL_NAMES) {
@@ -209,7 +228,8 @@ abstract class SetJsTest {
abstract fun constructors() abstract fun constructors()
Test fun nullAsValue() { @Test
fun nullAsValue() {
val set = createEmptyMutableSetWithNullableValues() val set = createEmptyMutableSetWithNullableValues()
assertTrue(set.isEmpty(), "Set should be empty") assertTrue(set.isEmpty(), "Set should be empty")
+1 -1
View File
@@ -11,7 +11,7 @@ class SimpleTest {
assertEquals("hello world!", message) assertEquals("hello world!", message)
} }
test fun cheese() { @test fun cheese() {
val name = "world" val name = "world"
val message = "bye $name!" val message = "bye $name!"
assertEquals("bye world!", message) assertEquals("bye world!", message)
@@ -14,23 +14,23 @@ class JavautilCollectionsTest {
val MAX_ELEMENT = 9 val MAX_ELEMENT = 9
val COMPARATOR = comparator { x: Int, y: Int -> if (x > y) 1 else if (x < y) -1 else 0 } val COMPARATOR = comparator { x: Int, y: Int -> if (x > y) 1 else if (x < y) -1 else 0 }
test fun maxWithComparator() { @test fun maxWithComparator() {
assertEquals(MAX_ELEMENT, Collections.max(TEST_LIST, COMPARATOR)) assertEquals(MAX_ELEMENT, Collections.max(TEST_LIST, COMPARATOR))
} }
test fun sort() { @test fun sort() {
val list = TEST_LIST.toArrayList() val list = TEST_LIST.toArrayList()
Collections.sort(list) Collections.sort(list)
assertEquals(SORTED_TEST_LIST, list) assertEquals(SORTED_TEST_LIST, list)
} }
test fun sortWithComparator() { @test fun sortWithComparator() {
val list = TEST_LIST.toArrayList() val list = TEST_LIST.toArrayList()
Collections.sort(list, COMPARATOR) Collections.sort(list, COMPARATOR)
assertEquals(SORTED_TEST_LIST, list) assertEquals(SORTED_TEST_LIST, list)
} }
test fun collectionToArray() { @test fun collectionToArray() {
val array = TEST_LIST.toTypedArray() val array = TEST_LIST.toTypedArray()
assertEquals(array.toList(), TEST_LIST) assertEquals(array.toList(), TEST_LIST)
} }
@@ -4,31 +4,31 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class BitwiseOperationsTest { class BitwiseOperationsTest {
test fun orForInt() { @test fun orForInt() {
assertEquals(3, 2 or 1) assertEquals(3, 2 or 1)
} }
test fun andForInt() { @test fun andForInt() {
assertEquals(0, 1 and 0) assertEquals(0, 1 and 0)
} }
test fun xorForInt() { @test fun xorForInt() {
assertEquals(1, 2 xor 3) assertEquals(1, 2 xor 3)
} }
test fun shlForInt() { @test fun shlForInt() {
assertEquals(4, 1 shl 2) assertEquals(4, 1 shl 2)
} }
test fun shrForInt() { @test fun shrForInt() {
assertEquals(1, 2 shr 1) assertEquals(1, 2 shr 1)
} }
test fun ushrForInt() { @test fun ushrForInt() {
assertEquals(2147483647, -1 ushr 1) assertEquals(2147483647, -1 ushr 1)
} }
test fun invForInt() { @test fun invForInt() {
assertEquals(0, (-1).inv()) assertEquals(0, (-1).inv())
} }
} }
@@ -34,7 +34,7 @@ public class RangeIterationJVMTest {
assertEquals(expectedElements, sequence.toList()) assertEquals(expectedElements, sequence.toList())
} }
test fun infiniteSteps() { @test fun infiniteSteps() {
doTest(0.0..5.0 step j.Double.POSITIVE_INFINITY, 0.0, 5.0, j.Double.POSITIVE_INFINITY, listOf(0.0)) doTest(0.0..5.0 step j.Double.POSITIVE_INFINITY, 0.0, 5.0, j.Double.POSITIVE_INFINITY, listOf(0.0))
doTest(0.0.toFloat()..5.0.toFloat() step j.Float.POSITIVE_INFINITY, 0.0.toFloat(), 5.0.toFloat(), j.Float.POSITIVE_INFINITY, doTest(0.0.toFloat()..5.0.toFloat() step j.Float.POSITIVE_INFINITY, 0.0.toFloat(), 5.0.toFloat(), j.Float.POSITIVE_INFINITY,
listOf<Float>(0.0.toFloat())) listOf<Float>(0.0.toFloat()))
@@ -43,7 +43,7 @@ public class RangeIterationJVMTest {
listOf<Float>(5.0.toFloat())) listOf<Float>(5.0.toFloat()))
} }
test fun nanEnds() { @test fun nanEnds() {
doTest(j.Double.NaN..5.0, j.Double.NaN, 5.0, 1.0, listOf()) doTest(j.Double.NaN..5.0, j.Double.NaN, 5.0, 1.0, listOf())
doTest(j.Float.NaN.toFloat()..5.0.toFloat(), j.Float.NaN, 5.0.toFloat(), 1.0.toFloat(), listOf()) doTest(j.Float.NaN.toFloat()..5.0.toFloat(), j.Float.NaN, 5.0.toFloat(), 1.0.toFloat(), listOf())
doTest(j.Double.NaN downTo 0.0, j.Double.NaN, 0.0, -1.0, listOf()) doTest(j.Double.NaN downTo 0.0, j.Double.NaN, 0.0, -1.0, listOf())
@@ -60,7 +60,7 @@ public class RangeIterationJVMTest {
doTest(j.Float.NaN downTo j.Float.NaN, j.Float.NaN, j.Float.NaN, -1.0.toFloat(), listOf()) doTest(j.Float.NaN downTo j.Float.NaN, j.Float.NaN, j.Float.NaN, -1.0.toFloat(), listOf())
} }
test fun maxValueToMaxValue() { @test fun maxValueToMaxValue() {
doTest(MaxI..MaxI, MaxI, MaxI, 1, listOf(MaxI)) doTest(MaxI..MaxI, MaxI, MaxI, 1, listOf(MaxI))
doTest(MaxB..MaxB, MaxB, MaxB, 1, listOf(MaxB)) doTest(MaxB..MaxB, MaxB, MaxB, 1, listOf(MaxB))
doTest(MaxS..MaxS, MaxS, MaxS, 1, listOf(MaxS)) doTest(MaxS..MaxS, MaxS, MaxS, 1, listOf(MaxS))
@@ -69,7 +69,7 @@ public class RangeIterationJVMTest {
doTest(MaxC..MaxC, MaxC, MaxC, 1, listOf(MaxC)) doTest(MaxC..MaxC, MaxC, MaxC, 1, listOf(MaxC))
} }
test fun maxValueMinusTwoToMaxValue() { @test fun maxValueMinusTwoToMaxValue() {
doTest((MaxI - 2)..MaxI, MaxI - 2, MaxI, 1, listOf(MaxI - 2, MaxI - 1, MaxI)) doTest((MaxI - 2)..MaxI, MaxI - 2, MaxI, 1, listOf(MaxI - 2, MaxI - 1, MaxI))
doTest((MaxB - 2).toByte()..MaxB, (MaxB - 2).toByte(), MaxB, 1, listOf((MaxB - 2).toByte(), (MaxB - 1).toByte(), MaxB)) doTest((MaxB - 2).toByte()..MaxB, (MaxB - 2).toByte(), MaxB, 1, listOf((MaxB - 2).toByte(), (MaxB - 1).toByte(), MaxB))
doTest((MaxS - 2).toShort()..MaxS, (MaxS - 2).toShort(), MaxS, 1, listOf((MaxS - 2).toShort(), (MaxS - 1).toShort(), MaxS)) doTest((MaxS - 2).toShort()..MaxS, (MaxS - 2).toShort(), MaxS, 1, listOf((MaxS - 2).toShort(), (MaxS - 1).toShort(), MaxS))
@@ -78,7 +78,7 @@ public class RangeIterationJVMTest {
doTest((MaxC - 2)..MaxC, (MaxC - 2), MaxC, 1, listOf((MaxC - 2), (MaxC - 1), MaxC)) doTest((MaxC - 2)..MaxC, (MaxC - 2), MaxC, 1, listOf((MaxC - 2), (MaxC - 1), MaxC))
} }
test fun maxValueToMinValue() { @test fun maxValueToMinValue() {
doTest(MaxI..MinI, MaxI, MinI, 1, listOf()) doTest(MaxI..MinI, MaxI, MinI, 1, listOf())
doTest(MaxB..MinB, MaxB, MinB, 1, listOf()) doTest(MaxB..MinB, MaxB, MinB, 1, listOf())
doTest(MaxS..MinS, MaxS, MinS, 1, listOf()) doTest(MaxS..MinS, MaxS, MinS, 1, listOf())
@@ -87,7 +87,7 @@ public class RangeIterationJVMTest {
doTest(MaxC..MinC, MaxC, MinC, 1, listOf()) doTest(MaxC..MinC, MaxC, MinC, 1, listOf())
} }
test fun progressionMaxValueToMaxValue() { @test fun progressionMaxValueToMaxValue() {
doTest(MaxI..MaxI step 1, MaxI, MaxI, 1, listOf(MaxI)) doTest(MaxI..MaxI step 1, MaxI, MaxI, 1, listOf(MaxI))
doTest(MaxB..MaxB step 1, MaxB, MaxB, 1, listOf(MaxB)) doTest(MaxB..MaxB step 1, MaxB, MaxB, 1, listOf(MaxB))
doTest(MaxS..MaxS step 1, MaxS, MaxS, 1, listOf(MaxS)) doTest(MaxS..MaxS step 1, MaxS, MaxS, 1, listOf(MaxS))
@@ -96,7 +96,7 @@ public class RangeIterationJVMTest {
doTest(MaxC..MaxC step 1, MaxC, MaxC, 1, listOf(MaxC)) doTest(MaxC..MaxC step 1, MaxC, MaxC, 1, listOf(MaxC))
} }
test fun progressionMaxValueMinusTwoToMaxValue() { @test fun progressionMaxValueMinusTwoToMaxValue() {
doTest((MaxI - 2)..MaxI step 2, MaxI - 2, MaxI, 2, listOf(MaxI - 2, MaxI)) doTest((MaxI - 2)..MaxI step 2, MaxI - 2, MaxI, 2, listOf(MaxI - 2, MaxI))
doTest((MaxB - 2).toByte()..MaxB step 2, (MaxB - 2).toByte(), MaxB, 2, listOf((MaxB - 2).toByte(), MaxB)) doTest((MaxB - 2).toByte()..MaxB step 2, (MaxB - 2).toByte(), MaxB, 2, listOf((MaxB - 2).toByte(), MaxB))
doTest((MaxS - 2).toShort()..MaxS step 2, (MaxS - 2).toShort(), MaxS, 2, listOf((MaxS - 2).toShort(), MaxS)) doTest((MaxS - 2).toShort()..MaxS step 2, (MaxS - 2).toShort(), MaxS, 2, listOf((MaxS - 2).toShort(), MaxS))
@@ -105,7 +105,7 @@ public class RangeIterationJVMTest {
doTest((MaxC - 2)..MaxC step 2, (MaxC - 2), MaxC, 2, listOf((MaxC - 2), MaxC)) doTest((MaxC - 2)..MaxC step 2, (MaxC - 2), MaxC, 2, listOf((MaxC - 2), MaxC))
} }
test fun progressionMaxValueToMinValue() { @test fun progressionMaxValueToMinValue() {
doTest(MaxI..MinI step 1, MaxI, MinI, 1, listOf()) doTest(MaxI..MinI step 1, MaxI, MinI, 1, listOf())
doTest(MaxB..MinB step 1, MaxB, MinB, 1, listOf()) doTest(MaxB..MinB step 1, MaxB, MinB, 1, listOf())
doTest(MaxS..MinS step 1, MaxS, MinS, 1, listOf()) doTest(MaxS..MinS step 1, MaxS, MinS, 1, listOf())
@@ -114,7 +114,7 @@ public class RangeIterationJVMTest {
doTest(MaxC..MinC step 1, MaxC, MinC, 1, listOf()) doTest(MaxC..MinC step 1, MaxC, MinC, 1, listOf())
} }
test fun progressionMinValueToMinValue() { @test fun progressionMinValueToMinValue() {
doTest(MinI..MinI step 1, MinI, MinI, 1, listOf(MinI)) doTest(MinI..MinI step 1, MinI, MinI, 1, listOf(MinI))
doTest(MinB..MinB step 1, MinB, MinB, 1, listOf(MinB)) doTest(MinB..MinB step 1, MinB, MinB, 1, listOf(MinB))
doTest(MinS..MinS step 1, MinS, MinS, 1, listOf(MinS)) doTest(MinS..MinS step 1, MinS, MinS, 1, listOf(MinS))
@@ -123,7 +123,7 @@ public class RangeIterationJVMTest {
doTest(MinC..MinC step 1, MinC, MinC, 1, listOf(MinC)) doTest(MinC..MinC step 1, MinC, MinC, 1, listOf(MinC))
} }
test fun inexactToMaxValue() { @test fun inexactToMaxValue() {
doTest((MaxI - 5)..MaxI step 3, MaxI - 5, MaxI, 3, listOf(MaxI - 5, MaxI - 2)) doTest((MaxI - 5)..MaxI step 3, MaxI - 5, MaxI, 3, listOf(MaxI - 5, MaxI - 2))
doTest((MaxB - 5).toByte()..MaxB step 3, (MaxB - 5).toByte(), MaxB, 3, listOf((MaxB - 5).toByte(), (MaxB - 2).toByte())) doTest((MaxB - 5).toByte()..MaxB step 3, (MaxB - 5).toByte(), MaxB, 3, listOf((MaxB - 5).toByte(), (MaxB - 2).toByte()))
doTest((MaxS - 5).toShort()..MaxS step 3, (MaxS - 5).toShort(), MaxS, 3, listOf((MaxS - 5).toShort(), (MaxS - 2).toShort())) doTest((MaxS - 5).toShort()..MaxS step 3, (MaxS - 5).toShort(), MaxS, 3, listOf((MaxS - 5).toShort(), (MaxS - 2).toShort()))
@@ -132,7 +132,7 @@ public class RangeIterationJVMTest {
doTest((MaxC - 5)..MaxC step 3, (MaxC - 5), MaxC, 3, listOf((MaxC - 5), (MaxC - 2))) doTest((MaxC - 5)..MaxC step 3, (MaxC - 5), MaxC, 3, listOf((MaxC - 5), (MaxC - 2)))
} }
test fun progressionDownToMinValue() { @test fun progressionDownToMinValue() {
doTest((MinI + 2) downTo MinI step 1, MinI + 2, MinI, -1, listOf(MinI + 2, MinI + 1, MinI)) doTest((MinI + 2) downTo MinI step 1, MinI + 2, MinI, -1, listOf(MinI + 2, MinI + 1, MinI))
doTest((MinB + 2).toByte() downTo MinB step 1, (MinB + 2).toByte(), MinB, -1, listOf((MinB + 2).toByte(), (MinB + 1).toByte(), MinB)) doTest((MinB + 2).toByte() downTo MinB step 1, (MinB + 2).toByte(), MinB, -1, listOf((MinB + 2).toByte(), (MinB + 1).toByte(), MinB))
doTest((MinS + 2).toShort() downTo MinS step 1, (MinS + 2).toShort(), MinS, -1, listOf((MinS + 2).toShort(), (MinS + 1).toShort(), MinS)) doTest((MinS + 2).toShort() downTo MinS step 1, (MinS + 2).toShort(), MinS, -1, listOf((MinS + 2).toShort(), (MinS + 1).toShort(), MinS))
@@ -141,7 +141,7 @@ public class RangeIterationJVMTest {
doTest((MinC + 2) downTo MinC step 1, (MinC + 2), MinC, -1, listOf((MinC + 2), (MinC + 1), MinC)) doTest((MinC + 2) downTo MinC step 1, (MinC + 2), MinC, -1, listOf((MinC + 2), (MinC + 1), MinC))
} }
test fun inexactDownToMinValue() { @test fun inexactDownToMinValue() {
doTest((MinI + 5) downTo MinI step 3, MinI + 5, MinI, -3, listOf(MinI + 5, MinI + 2)) doTest((MinI + 5) downTo MinI step 3, MinI + 5, MinI, -3, listOf(MinI + 5, MinI + 2))
doTest((MinB + 5).toByte() downTo MinB step 3, (MinB + 5).toByte(), MinB, -3, listOf((MinB + 5).toByte(), (MinB + 2).toByte())) doTest((MinB + 5).toByte() downTo MinB step 3, (MinB + 5).toByte(), MinB, -3, listOf((MinB + 5).toByte(), (MinB + 2).toByte()))
doTest((MinS + 5).toShort() downTo MinS step 3, (MinS + 5).toShort(), MinS, -3, listOf((MinS + 5).toShort(), (MinS + 2).toShort())) doTest((MinS + 5).toShort() downTo MinS step 3, (MinS + 5).toShort(), MinS, -3, listOf((MinS + 5).toShort(), (MinS + 2).toShort()))
@@ -22,7 +22,7 @@ public class RangeIterationTest {
assertEquals(expectedElements, sequence.toList()) assertEquals(expectedElements, sequence.toList())
} }
test fun emptyConstant() { @test fun emptyConstant() {
doTest(IntRange.EMPTY, 1, 0, 1, listOf()) doTest(IntRange.EMPTY, 1, 0, 1, listOf())
doTest(ByteRange.EMPTY, 1.toByte(), 0.toByte(), 1, listOf()) doTest(ByteRange.EMPTY, 1.toByte(), 0.toByte(), 1, listOf())
doTest(ShortRange.EMPTY, 1.toShort(), 0.toShort(), 1, listOf()) doTest(ShortRange.EMPTY, 1.toShort(), 0.toShort(), 1, listOf())
@@ -34,7 +34,7 @@ public class RangeIterationTest {
doTest(FloatRange.EMPTY, 1.0.toFloat(), 0.0.toFloat(), 1.0.toFloat(), listOf()) doTest(FloatRange.EMPTY, 1.0.toFloat(), 0.0.toFloat(), 1.0.toFloat(), listOf())
} }
test fun emptyRange() { @test fun emptyRange() {
doTest(10..5, 10, 5, 1, listOf()) doTest(10..5, 10, 5, 1, listOf())
doTest(10.toByte()..(-5).toByte(), 10.toByte(), (-5).toByte(), 1, listOf()) doTest(10.toByte()..(-5).toByte(), 10.toByte(), (-5).toByte(), 1, listOf())
doTest(10.toShort()..(-5).toShort(), 10.toShort(), (-5).toShort(), 1, listOf()) doTest(10.toShort()..(-5).toShort(), 10.toShort(), (-5).toShort(), 1, listOf())
@@ -46,7 +46,7 @@ public class RangeIterationTest {
doTest(5.0.toFloat()..-1.0.toFloat(), 5.0.toFloat(), -1.0.toFloat(), 1.toFloat(), listOf()) doTest(5.0.toFloat()..-1.0.toFloat(), 5.0.toFloat(), -1.0.toFloat(), 1.toFloat(), listOf())
} }
test fun oneElementRange() { @test fun oneElementRange() {
doTest(5..5, 5, 5, 1, listOf(5)) doTest(5..5, 5, 5, 1, listOf(5))
doTest(5.toByte()..5.toByte(), 5.toByte(), 5.toByte(), 1, listOf(5.toByte())) doTest(5.toByte()..5.toByte(), 5.toByte(), 5.toByte(), 1, listOf(5.toByte()))
doTest(5.toShort()..5.toShort(), 5.toShort(), 5.toShort(), 1, listOf(5.toShort())) doTest(5.toShort()..5.toShort(), 5.toShort(), 5.toShort(), 1, listOf(5.toShort()))
@@ -58,7 +58,7 @@ public class RangeIterationTest {
doTest(5.0.toFloat()..5.0.toFloat(), 5.0.toFloat(), 5.0.toFloat(), 1.toFloat(), listOf(5.0.toFloat())) doTest(5.0.toFloat()..5.0.toFloat(), 5.0.toFloat(), 5.0.toFloat(), 1.toFloat(), listOf(5.0.toFloat()))
} }
test fun simpleRange() { @test fun simpleRange() {
doTest(3..9, 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest(3..9, 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
doTest(3.toByte()..9.toByte(), 3.toByte(), 9.toByte(), 1, listOf<Byte>(3, 4, 5, 6, 7, 8, 9)) doTest(3.toByte()..9.toByte(), 3.toByte(), 9.toByte(), 1, listOf<Byte>(3, 4, 5, 6, 7, 8, 9))
doTest(3.toShort()..9.toShort(), 3.toShort(), 9.toShort(), 1, listOf<Short>(3, 4, 5, 6, 7, 8, 9)) doTest(3.toShort()..9.toShort(), 3.toShort(), 9.toShort(), 1, listOf<Short>(3, 4, 5, 6, 7, 8, 9))
@@ -72,7 +72,7 @@ public class RangeIterationTest {
} }
test fun simpleRangeWithNonConstantEnds() { @test fun simpleRangeWithNonConstantEnds() {
doTest((1 + 2)..(10 - 1), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest((1 + 2)..(10 - 1), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
doTest((1.toByte() + 2.toByte()).toByte()..(10.toByte() - 1.toByte()).toByte(), 3.toByte(), 9.toByte(), 1, listOf<Byte>(3, 4, 5, 6, 7, 8, 9)) doTest((1.toByte() + 2.toByte()).toByte()..(10.toByte() - 1.toByte()).toByte(), 3.toByte(), 9.toByte(), 1, listOf<Byte>(3, 4, 5, 6, 7, 8, 9))
doTest((1.toShort() + 2.toShort()).toShort()..(10.toShort() - 1.toShort()).toShort(), 3.toShort(), 9.toShort(), 1, listOf<Short>(3, 4, 5, 6, 7, 8, 9)) doTest((1.toShort() + 2.toShort()).toShort()..(10.toShort() - 1.toShort()).toShort(), 3.toShort(), 9.toShort(), 1, listOf<Short>(3, 4, 5, 6, 7, 8, 9))
@@ -85,7 +85,7 @@ public class RangeIterationTest {
listOf<Float>(3.0.toFloat(), 4.0.toFloat(), 5.0.toFloat(), 6.0.toFloat(), 7.0.toFloat(), 8.0.toFloat(), 9.0.toFloat())) listOf<Float>(3.0.toFloat(), 4.0.toFloat(), 5.0.toFloat(), 6.0.toFloat(), 7.0.toFloat(), 8.0.toFloat(), 9.0.toFloat()))
} }
test fun openRange() { @test fun openRange() {
doTest(1 until 5, 1, 4, 1, listOf(1, 2, 3, 4)) doTest(1 until 5, 1, 4, 1, listOf(1, 2, 3, 4))
doTest(1.toByte() until 5.toByte(), 1.toByte(), 4.toByte(), 1, listOf<Byte>(1, 2, 3, 4)) doTest(1.toByte() until 5.toByte(), 1.toByte(), 4.toByte(), 1, listOf<Byte>(1, 2, 3, 4))
doTest(1.toShort() until 5.toShort(), 1.toShort(), 4.toShort(), 1, listOf<Short>(1, 2, 3, 4)) doTest(1.toShort() until 5.toShort(), 1.toShort(), 4.toShort(), 1, listOf<Short>(1, 2, 3, 4))
@@ -94,7 +94,7 @@ public class RangeIterationTest {
} }
test fun emptyDownto() { @test fun emptyDownto() {
doTest(5 downTo 10, 5, 10, -1, listOf()) doTest(5 downTo 10, 5, 10, -1, listOf())
doTest(5.toByte() downTo 10.toByte(), 5.toByte(), 10.toByte(), -1, listOf()) doTest(5.toByte() downTo 10.toByte(), 5.toByte(), 10.toByte(), -1, listOf())
doTest(5.toShort() downTo 10.toShort(), 5.toShort(), 10.toShort(), -1, listOf()) doTest(5.toShort() downTo 10.toShort(), 5.toShort(), 10.toShort(), -1, listOf())
@@ -106,7 +106,7 @@ public class RangeIterationTest {
doTest(-1.0.toFloat() downTo 5.0.toFloat(), -1.0.toFloat(), 5.0.toFloat(), -1.0.toFloat(), listOf()) doTest(-1.0.toFloat() downTo 5.0.toFloat(), -1.0.toFloat(), 5.0.toFloat(), -1.0.toFloat(), listOf())
} }
test fun oneElementDownTo() { @test fun oneElementDownTo() {
doTest(5 downTo 5, 5, 5, -1, listOf(5)) doTest(5 downTo 5, 5, 5, -1, listOf(5))
doTest(5.toByte() downTo 5.toByte(), 5.toByte(), 5.toByte(), -1, listOf(5.toByte())) doTest(5.toByte() downTo 5.toByte(), 5.toByte(), 5.toByte(), -1, listOf(5.toByte()))
doTest(5.toShort() downTo 5.toShort(), 5.toShort(), 5.toShort(), -1, listOf(5.toShort())) doTest(5.toShort() downTo 5.toShort(), 5.toShort(), 5.toShort(), -1, listOf(5.toShort()))
@@ -118,7 +118,7 @@ public class RangeIterationTest {
doTest(5.0.toFloat() downTo 5.0.toFloat(), 5.0.toFloat(), 5.0.toFloat(), -1.0.toFloat(), listOf(5.0.toFloat())) doTest(5.0.toFloat() downTo 5.0.toFloat(), 5.0.toFloat(), 5.0.toFloat(), -1.0.toFloat(), listOf(5.0.toFloat()))
} }
test fun simpleDownTo() { @test fun simpleDownTo() {
doTest(9 downTo 3, 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3)) doTest(9 downTo 3, 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3))
doTest(9.toByte() downTo 3.toByte(), 9.toByte(), 3.toByte(), -1, listOf<Byte>(9, 8, 7, 6, 5, 4, 3)) doTest(9.toByte() downTo 3.toByte(), 9.toByte(), 3.toByte(), -1, listOf<Byte>(9, 8, 7, 6, 5, 4, 3))
doTest(9.toShort() downTo 3.toShort(), 9.toShort(), 3.toShort(), -1, listOf<Short>(9, 8, 7, 6, 5, 4, 3)) doTest(9.toShort() downTo 3.toShort(), 9.toShort(), 3.toShort(), -1, listOf<Short>(9, 8, 7, 6, 5, 4, 3))
@@ -132,7 +132,7 @@ public class RangeIterationTest {
} }
test fun simpleSteppedRange() { @test fun simpleSteppedRange() {
doTest(3..9 step 2, 3, 9, 2, listOf(3, 5, 7, 9)) doTest(3..9 step 2, 3, 9, 2, listOf(3, 5, 7, 9))
doTest(3.toByte()..9.toByte() step 2, 3.toByte(), 9.toByte(), 2, listOf<Byte>(3, 5, 7, 9)) doTest(3.toByte()..9.toByte() step 2, 3.toByte(), 9.toByte(), 2, listOf<Byte>(3, 5, 7, 9))
doTest(3.toShort()..9.toShort() step 2, 3.toShort(), 9.toShort(), 2, listOf<Short>(3, 5, 7, 9)) doTest(3.toShort()..9.toShort() step 2, 3.toShort(), 9.toShort(), 2, listOf<Short>(3, 5, 7, 9))
@@ -145,7 +145,7 @@ public class RangeIterationTest {
listOf<Float>(4.0.toFloat(), 4.5.toFloat(), 5.0.toFloat(), 5.5.toFloat(), 6.0.toFloat())) listOf<Float>(4.0.toFloat(), 4.5.toFloat(), 5.0.toFloat(), 5.5.toFloat(), 6.0.toFloat()))
} }
test fun simpleSteppedDownTo() { @test fun simpleSteppedDownTo() {
doTest(9 downTo 3 step 2, 9, 3, -2, listOf(9, 7, 5, 3)) doTest(9 downTo 3 step 2, 9, 3, -2, listOf(9, 7, 5, 3))
doTest(9.toByte() downTo 3.toByte() step 2, 9.toByte(), 3.toByte(), -2, listOf<Byte>(9, 7, 5, 3)) doTest(9.toByte() downTo 3.toByte() step 2, 9.toByte(), 3.toByte(), -2, listOf<Byte>(9, 7, 5, 3))
doTest(9.toShort() downTo 3.toShort() step 2, 9.toShort(), 3.toShort(), -2, listOf<Short>(9, 7, 5, 3)) doTest(9.toShort() downTo 3.toShort() step 2, 9.toShort(), 3.toShort(), -2, listOf<Short>(9, 7, 5, 3))
@@ -160,7 +160,7 @@ public class RangeIterationTest {
// 'inexact' means last element is not equal to sequence end // 'inexact' means last element is not equal to sequence end
test fun inexactSteppedRange() { @test fun inexactSteppedRange() {
doTest(3..8 step 2, 3, 8, 2, listOf(3, 5, 7)) doTest(3..8 step 2, 3, 8, 2, listOf(3, 5, 7))
doTest(3.toByte()..8.toByte() step 2, 3.toByte(), 8.toByte(), 2, listOf<Byte>(3, 5, 7)) doTest(3.toByte()..8.toByte() step 2, 3.toByte(), 8.toByte(), 2, listOf<Byte>(3, 5, 7))
doTest(3.toShort()..8.toShort() step 2, 3.toShort(), 8.toShort(), 2, listOf<Short>(3, 5, 7)) doTest(3.toShort()..8.toShort() step 2, 3.toShort(), 8.toShort(), 2, listOf<Short>(3, 5, 7))
@@ -174,7 +174,7 @@ public class RangeIterationTest {
} }
// 'inexact' means last element is not equal to sequence end // 'inexact' means last element is not equal to sequence end
test fun inexactSteppedDownTo() { @test fun inexactSteppedDownTo() {
doTest(8 downTo 3 step 2, 8, 3, -2, listOf(8, 6, 4)) doTest(8 downTo 3 step 2, 8, 3, -2, listOf(8, 6, 4))
doTest(8.toByte() downTo 3.toByte() step 2, 8.toByte(), 3.toByte(), -2, listOf<Byte>(8, 6, 4)) doTest(8.toByte() downTo 3.toByte() step 2, 8.toByte(), 3.toByte(), -2, listOf<Byte>(8, 6, 4))
doTest(8.toShort() downTo 3.toShort() step 2, 8.toShort(), 3.toShort(), -2, listOf<Short>(8, 6, 4)) doTest(8.toShort() downTo 3.toShort() step 2, 8.toShort(), 3.toShort(), -2, listOf<Short>(8, 6, 4))
@@ -188,7 +188,7 @@ public class RangeIterationTest {
} }
test fun reversedEmptyRange() { @test fun reversedEmptyRange() {
doTest((5..3).reversed(), 3, 5, -1, listOf()) doTest((5..3).reversed(), 3, 5, -1, listOf())
doTest((5.toByte()..3.toByte()).reversed(), 3.toByte(), 5.toByte(), -1, listOf()) doTest((5.toByte()..3.toByte()).reversed(), 3.toByte(), 5.toByte(), -1, listOf())
doTest((5.toShort()..3.toShort()).reversed(), 3.toShort(), 5.toShort(), -1, listOf()) doTest((5.toShort()..3.toShort()).reversed(), 3.toShort(), 5.toShort(), -1, listOf())
@@ -200,7 +200,7 @@ public class RangeIterationTest {
doTest((5.0.toFloat()..3.0.toFloat()).reversed(), 3.0.toFloat(), 5.0.toFloat(), -1.toFloat(), listOf()) doTest((5.0.toFloat()..3.0.toFloat()).reversed(), 3.0.toFloat(), 5.0.toFloat(), -1.toFloat(), listOf())
} }
test fun reversedEmptyBackSequence() { @test fun reversedEmptyBackSequence() {
doTest((3 downTo 5).reversed(), 5, 3, 1, listOf()) doTest((3 downTo 5).reversed(), 5, 3, 1, listOf())
doTest((3.toByte() downTo 5.toByte()).reversed(), 5.toByte(), 3.toByte(), 1, listOf()) doTest((3.toByte() downTo 5.toByte()).reversed(), 5.toByte(), 3.toByte(), 1, listOf())
doTest((3.toShort() downTo 5.toShort()).reversed(), 5.toShort(), 3.toShort(), 1, listOf()) doTest((3.toShort() downTo 5.toShort()).reversed(), 5.toShort(), 3.toShort(), 1, listOf())
@@ -212,7 +212,7 @@ public class RangeIterationTest {
doTest((3.0.toFloat() downTo 5.0.toFloat()).reversed(), 5.0.toFloat(), 3.0.toFloat(), 1.toFloat(), listOf()) doTest((3.0.toFloat() downTo 5.0.toFloat()).reversed(), 5.0.toFloat(), 3.0.toFloat(), 1.toFloat(), listOf())
} }
test fun reversedRange() { @test fun reversedRange() {
doTest((3..5).reversed(), 5, 3, -1, listOf(5, 4, 3)) doTest((3..5).reversed(), 5, 3, -1, listOf(5, 4, 3))
doTest((3.toByte()..5.toByte()).reversed(), 5.toByte(), 3.toByte(), -1, listOf<Byte>(5, 4, 3)) doTest((3.toByte()..5.toByte()).reversed(), 5.toByte(), 3.toByte(), -1, listOf<Byte>(5, 4, 3))
doTest((3.toShort()..5.toShort()).reversed(), 5.toShort(), 3.toShort(), -1, listOf<Short>(5, 4, 3)) doTest((3.toShort()..5.toShort()).reversed(), 5.toShort(), 3.toShort(), -1, listOf<Short>(5, 4, 3))
@@ -225,7 +225,7 @@ public class RangeIterationTest {
listOf<Float>(5.0.toFloat(), 4.0.toFloat(), 3.0.toFloat())) listOf<Float>(5.0.toFloat(), 4.0.toFloat(), 3.0.toFloat()))
} }
test fun reversedBackSequence() { @test fun reversedBackSequence() {
doTest((5 downTo 3).reversed(), 3, 5, 1, listOf(3, 4, 5)) doTest((5 downTo 3).reversed(), 3, 5, 1, listOf(3, 4, 5))
doTest((5.toByte() downTo 3.toByte()).reversed(), 3.toByte(), 5.toByte(), 1, listOf<Byte>(3, 4, 5)) doTest((5.toByte() downTo 3.toByte()).reversed(), 3.toByte(), 5.toByte(), 1, listOf<Byte>(3, 4, 5))
doTest((5.toShort() downTo 3.toShort()).reversed(), 3.toShort(), 5.toShort(), 1, listOf<Short>(3, 4, 5)) doTest((5.toShort() downTo 3.toShort()).reversed(), 3.toShort(), 5.toShort(), 1, listOf<Short>(3, 4, 5))
@@ -238,7 +238,7 @@ public class RangeIterationTest {
listOf<Float>(3.0.toFloat(), 4.0.toFloat(), 5.0.toFloat())) listOf<Float>(3.0.toFloat(), 4.0.toFloat(), 5.0.toFloat()))
} }
test fun reversedSimpleSteppedRange() { @test fun reversedSimpleSteppedRange() {
doTest((3..9 step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3)) doTest((3..9 step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3))
doTest((3.toByte()..9.toByte() step 2).reversed(), 9.toByte(), 3.toByte(), -2, listOf<Byte>(9, 7, 5, 3)) doTest((3.toByte()..9.toByte() step 2).reversed(), 9.toByte(), 3.toByte(), -2, listOf<Byte>(9, 7, 5, 3))
doTest((3.toShort()..9.toShort() step 2).reversed(), 9.toShort(), 3.toShort(), -2, listOf<Short>(9, 7, 5, 3)) doTest((3.toShort()..9.toShort() step 2).reversed(), 9.toShort(), 3.toShort(), -2, listOf<Short>(9, 7, 5, 3))
@@ -252,7 +252,7 @@ public class RangeIterationTest {
} }
// 'inexact' means last element is not equal to sequence end // 'inexact' means last element is not equal to sequence end
test fun reversedInexactSteppedDownTo() { @test fun reversedInexactSteppedDownTo() {
doTest((8 downTo 3 step 2).reversed(), 3, 8, 2, listOf(3, 5, 7)) doTest((8 downTo 3 step 2).reversed(), 3, 8, 2, listOf(3, 5, 7))
doTest((8.toByte() downTo 3.toByte() step 2).reversed(), 3.toByte(), 8.toByte(), 2, listOf<Byte>(3, 5, 7)) doTest((8.toByte() downTo 3.toByte() step 2).reversed(), 3.toByte(), 8.toByte(), 2, listOf<Byte>(3, 5, 7))
doTest((8.toShort() downTo 3.toShort() step 2).reversed(), 3.toShort(), 8.toShort(), 2, listOf<Short>(3, 5, 7)) doTest((8.toShort() downTo 3.toShort() step 2).reversed(), 3.toShort(), 8.toShort(), 2, listOf<Short>(3, 5, 7))
@@ -7,14 +7,14 @@ import kotlin.test.*
public class RangeJVMTest { public class RangeJVMTest {
test fun doubleRange() { @test fun doubleRange() {
val range = -1.0..3.14159265358979 val range = -1.0..3.14159265358979
assertFalse(jDouble.NEGATIVE_INFINITY in range) assertFalse(jDouble.NEGATIVE_INFINITY in range)
assertFalse(jDouble.POSITIVE_INFINITY in range) assertFalse(jDouble.POSITIVE_INFINITY in range)
assertFalse(jDouble.NaN in range) assertFalse(jDouble.NaN in range)
} }
test fun floatRange() { @test fun floatRange() {
val range = -1.0f..3.14159f val range = -1.0f..3.14159f
assertFalse(jFloat.NEGATIVE_INFINITY in range) assertFalse(jFloat.NEGATIVE_INFINITY in range)
assertFalse(jFloat.POSITIVE_INFINITY in range) assertFalse(jFloat.POSITIVE_INFINITY in range)
@@ -22,7 +22,7 @@ public class RangeJVMTest {
assertFalse(jFloat.NaN in range) assertFalse(jFloat.NaN in range)
} }
test fun illegalProgressionCreation() { @test fun illegalProgressionCreation() {
fun assertFailsWithIllegalArgument(f: () -> Unit) = assertFailsWith(IllegalArgumentException::class, block = f) fun assertFailsWithIllegalArgument(f: () -> Unit) = assertFailsWith(IllegalArgumentException::class, block = f)
// create Progression explicitly with increment = 0 // create Progression explicitly with increment = 0
assertFailsWithIllegalArgument { IntProgression(0, 5, 0) } assertFailsWithIllegalArgument { IntProgression(0, 5, 0) }
+11 -11
View File
@@ -4,7 +4,7 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
public class RangeTest { public class RangeTest {
test fun intRange() { @test fun intRange() {
val range = -5..9 val range = -5..9
assertFalse(-1000 in range) assertFalse(-1000 in range)
assertFalse(-6 in range) assertFalse(-6 in range)
@@ -36,7 +36,7 @@ public class RangeTest {
assertTrue(fails { 1 until Int.MIN_VALUE } is IllegalArgumentException) assertTrue(fails { 1 until Int.MIN_VALUE } is IllegalArgumentException)
} }
test fun byteRange() { @test fun byteRange() {
val range = (-5).toByte()..9.toByte() val range = (-5).toByte()..9.toByte()
assertFalse((-100).toByte() in range) assertFalse((-100).toByte() in range)
assertFalse((-6).toByte() in range) assertFalse((-6).toByte() in range)
@@ -70,7 +70,7 @@ public class RangeTest {
} }
test fun shortRange() { @test fun shortRange() {
val range = (-5).toShort()..9.toShort() val range = (-5).toShort()..9.toShort()
assertFalse((-1000).toShort() in range) assertFalse((-1000).toShort() in range)
assertFalse((-6).toShort() in range) assertFalse((-6).toShort() in range)
@@ -102,7 +102,7 @@ public class RangeTest {
assertTrue(fails { 0.toShort() until Short.MIN_VALUE } is IllegalArgumentException) assertTrue(fails { 0.toShort() until Short.MIN_VALUE } is IllegalArgumentException)
} }
test fun longRange() { @test fun longRange() {
val range = -5L..9L val range = -5L..9L
assertFalse(-10000000L in range) assertFalse(-10000000L in range)
assertFalse(-6L in range) assertFalse(-6L in range)
@@ -135,7 +135,7 @@ public class RangeTest {
} }
test fun charRange() { @test fun charRange() {
val range = 'c'..'w' val range = 'c'..'w'
assertFalse('0' in range) assertFalse('0' in range)
assertFalse('b' in range) assertFalse('b' in range)
@@ -159,7 +159,7 @@ public class RangeTest {
assertTrue(fails { 'A' until '\u0000' } is IllegalArgumentException) assertTrue(fails { 'A' until '\u0000' } is IllegalArgumentException)
} }
test fun doubleRange() { @test fun doubleRange() {
val range = -1.0..3.14159265358979 val range = -1.0..3.14159265358979
assertFalse(-1e200 in range) assertFalse(-1e200 in range)
assertFalse(-100.0 in range) assertFalse(-100.0 in range)
@@ -185,7 +185,7 @@ public class RangeTest {
assertTrue(1.toFloat() in range) assertTrue(1.toFloat() in range)
} }
test fun floatRange() { @test fun floatRange() {
val range = -1.0f..3.14159f val range = -1.0f..3.14159f
assertFalse(-1e30f in range) assertFalse(-1e30f in range)
assertFalse(-100.0f in range) assertFalse(-100.0f in range)
@@ -213,7 +213,7 @@ public class RangeTest {
assertFalse(Double.MAX_VALUE in range) assertFalse(Double.MAX_VALUE in range)
} }
test fun isEmpty() { @test fun isEmpty() {
assertTrue((2..1).isEmpty()) assertTrue((2..1).isEmpty())
assertTrue((2L..0L).isEmpty()) assertTrue((2L..0L).isEmpty())
assertTrue((1.toShort()..-1.toShort()).isEmpty()) assertTrue((1.toShort()..-1.toShort()).isEmpty())
@@ -232,7 +232,7 @@ public class RangeTest {
assertTrue(("range".."progression").isEmpty()) assertTrue(("range".."progression").isEmpty())
} }
test fun emptyEquals() { @test fun emptyEquals() {
assertTrue(IntRange.EMPTY == IntRange.EMPTY) assertTrue(IntRange.EMPTY == IntRange.EMPTY)
assertEquals(IntRange.EMPTY, IntRange.EMPTY) assertEquals(IntRange.EMPTY, IntRange.EMPTY)
assertEquals(0L..42L, 0L..42L) assertEquals(0L..42L, 0L..42L)
@@ -259,7 +259,7 @@ public class RangeTest {
assertFalse(("aa".."bb") == ("aaa".."bbb")) assertFalse(("aa".."bb") == ("aaa".."bbb"))
} }
test fun emptyHashCode() { @test fun emptyHashCode() {
assertEquals((0..42).hashCode(), (0..42).hashCode()) assertEquals((0..42).hashCode(), (0..42).hashCode())
assertEquals((1.23..4.56).hashCode(), (1.23..4.56).hashCode()) assertEquals((1.23..4.56).hashCode(), (1.23..4.56).hashCode())
@@ -279,7 +279,7 @@ public class RangeTest {
assertEquals(("range".."progression").hashCode(), ("hashcode".."equals").hashCode()) assertEquals(("range".."progression").hashCode(), ("hashcode".."equals").hashCode())
} }
test fun comparableRange() { @test fun comparableRange() {
val range = "island".."isle" val range = "island".."isle"
assertFalse("apple" in range) assertFalse("apple" in range)
assertFalse("icicle" in range) assertFalse("icicle" in range)
@@ -41,7 +41,7 @@ val EXPECTED = """
class StringExpressionExampleTest { class StringExpressionExampleTest {
val customer = Customer("James", arrayListOf(Product("Beer", 1.99), Product("Wine", 5.99))) val customer = Customer("James", arrayListOf(Product("Beer", 1.99), Product("Wine", 5.99)))
test fun testExpressions(): Unit { @test fun testExpressions(): Unit {
assertEquals(EXPECTED, customerTemplate(customer)) assertEquals(EXPECTED, customerTemplate(customer))
} }
} }
@@ -17,7 +17,8 @@ class CoercionTest {
val n3 = n coerceIn 2..5 val n3 = n coerceIn 2..5
} }
Test fun coercionsInt() { @Test
fun coercionsInt() {
expect(5) { 5.coerceAtLeast(1) } expect(5) { 5.coerceAtLeast(1) }
expect(5) { 1.coerceAtLeast(5) } expect(5) { 1.coerceAtLeast(5) }
expect(1) { 5.coerceAtMost(1) } expect(1) { 5.coerceAtMost(1) }
@@ -39,7 +40,8 @@ class CoercionTest {
fails { 1.coerceIn(1..0) } fails { 1.coerceIn(1..0) }
} }
Test fun coercionsLong() { @Test
fun coercionsLong() {
expect(5L) { 5L.coerceAtLeast(1L) } expect(5L) { 5L.coerceAtLeast(1L) }
expect(5L) { 1L.coerceAtLeast(5L) } expect(5L) { 1L.coerceAtLeast(5L) }
expect(1L) { 5L.coerceAtMost(1L) } expect(1L) { 5L.coerceAtMost(1L) }
@@ -62,7 +64,8 @@ class CoercionTest {
} }
Test fun coercionsDouble() { @Test
fun coercionsDouble() {
expect(5.0) { 5.0.coerceAtLeast(1.0) } expect(5.0) { 5.0.coerceAtLeast(1.0) }
expect(5.0) { 1.0.coerceAtLeast(5.0) } expect(5.0) { 1.0.coerceAtLeast(5.0) }
expect(1.0) { 5.0.coerceAtMost(1.0) } expect(1.0) { 5.0.coerceAtMost(1.0) }
@@ -84,7 +87,8 @@ class CoercionTest {
fails { 1.0.coerceIn(1.0..0.0) } fails { 1.0.coerceIn(1.0..0.0) }
} }
Test fun coercionsComparable() { @Test
fun coercionsComparable() {
val v = 0..10 map { ComparableNumber(it) } val v = 0..10 map { ComparableNumber(it) }
expect(5) { v[5].coerceAtLeast(v[1]).value } expect(5) { v[5].coerceAtLeast(v[1]).value }

Some files were not shown because too many files have changed in this diff Show More