fun Routing.api() { route("news") { get { val newsData = NewsUseCase.getAcceptedNews() call.respond(newsData) } get("propositions") { requireSecret() val newsData = NewsUseCase.getPropositions() call.respond(newsData) } } // ... }
这是在Kotlin Test中定义的测试用例:
1 2 3 4 5 6 7 8
classMyTests : StringSpec({ "length should return size of string" { "hello".length shouldBe 5 } "startsWith should test for a prefix" { "world" should startWith("wor") } })
operatorfun<T> Iterable<T>.plus(element: T): List<T> { if (thisis Collection) returnthis.plus(element) val result = ArrayList<T>() result.addAll(this) result.add(element) return result }
inlinefun<T, R> Iterable<T>.map( transform: (T) -> R ): List<R> { val size = if (thisis Collection<*>) this.size else10 val destination = ArrayList<R>(size) for (item inthis) destination.add(transform(item)) return destination }
而不是不可变集合:
1 2 3 4 5 6 7 8 9
// This is not how map is implemented inlinefun<T, R> Iterable<T>.map( transform: (T) -> R ): List<R> { var destination = listOf<R>() for (item inthis) destination += transform(item) return destination }
inlinefunrequestNewToken( hasToken: Boolean, crossinline onRefresh: () -> Unit, noinline onGenerate: () -> Unit ) { if (hasToken) { httpCall("get-token", onGenerate) // We must use // noinline to pass function as an argument to a // function that is not inlined } else { httpCall("refresh-token") { onRefresh() // We must use crossinline to // inline function in a context where // non-local return is not allowed onGenerate() } } }
val fibonacci: Sequence<BigDecimal> = sequence { var current = 1.toBigDecimal() var prev = 1.toBigDecimal() yield(prev) while (true) { yield(current) val temp = prev prev = current current += temp } }
// BAD SOLUTION, DO NOT USE COLLECTIONS FOR // POSSIBLY BIG FILES File("ChicagoCrimes.csv") .readLines() .drop(1) // Drop descriptions of the columns .mapNotNull { it.split(",").getOrNull(6) } // Find description .filter { "CANNABIS"in it } .count() .let(::println)
这段程序在我电脑上的运行结果是:
script
1
OutOfMemoryError.n> Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
File("ChicagoCrimes.csv").useLines { lines -> // The type of `lines` is Sequence<String> lines.drop(1) // Drop descriptions of the columns .mapNotNull { it.split(",").getOrNull(6) } // Find description .filter { "CANNABIS"in it } .count() .let { println(it) } // 318185 }
@Suppress("UNCHECKED_CAST") funrunCallLoop(): R { while (true) { // Note: cont is set to null in DeepRecursiveScopeImpl.resumeWith when the whole computation completes val result = this.result val cont = this.cont ?: return (result as Result<R>).getOrThrow() // done -- final result // The order of comparison is important here for that case of rogue class with broken equals if (UNDEFINED_RESULT == result) { // call "function" with "value" using "cont" as completion val r = try { // This is block.startCoroutine(this, value, cont) function.startCoroutineUninterceptedOrReturn(this, value, cont) } catch (e: Throwable) { cont.resumeWithException(e) continue } // If the function returns without suspension -- calls its continuation immediately if (r !== COROUTINE_SUSPENDED) cont.resume(r as R) } else { // we returned from a crossFunctionCompletion trampoline -- call resume here this.result = UNDEFINED_RESULT // reset result back cont.resumeWith(result) } } }