val time =measureTimeMillis {val one =doSomethingUsefulOne()val two =doSomethingUsefulTwo()println("The answer is ${one + two}")}println("Completed in $time ms")
📋 Hepsi
// TODOfuncalcTaxes(): BigDecimal=TODO("Waiting for feedback from accounting")// Koşullu kullanım (Conditional expressions)if (a > b) a else b// Instance checkwhen (x) {is Foo ->// ...is Bar ->// ...else->// ...}(obj !is String)// Rangefor (x in1..10 step 2) {}// Collectionsval fruits =listOf("banana", "avocado", "apple", "kiwifruit")fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) }("jane@example.com"!in emailsList)// Filtrelemelist.filter { x -> x >0 }// Lazyval p: Stringbylazy {// compute the string}// Extension functionsfunString.spaceToCamelCase() { /* ... */ }// Null println(files?.size ?: "empty")val mapped =value?.let { transformValue(it) } ?: defaultValueval email = values["email"] ?: throwIllegalStateException("Email is missing!")// Try-Catchval email = values["email"] ?: throwIllegalStateException("Email is missing!")funtransform(color: String): Int {returnwhen (color) {"Red"->0"Green"->1"Blue"->2else->throwIllegalArgumentException("Invalid color param value") }}funtest() {val result =try {count() } catch (e: ArithmeticException) {throwIllegalStateException(e) }// Working with result}funtransform(color: String): Int=when (color) {"Red"->0"Green"->1"Blue"->2else->throwIllegalArgumentException("Invalid color param value")}// Java 7's try with resourcesval stream = Files.newInputStream(Paths.get("/some/file.txt"))stream.buffered().reader().use { reader ->println(reader.readText())}// Convenient form for a generic function that requires the generic type information// public final class Gson {// ...// public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {// ...inlinefun <reifiedT: Any> Gson.fromJson(json: JsonElement): T=this.fromJson(json, T::class.java)// Swap varvar a =1var b =2a = b.also { b = a }
Functions vs Properties
In some cases functions with no arguments might be interchangeable with read-only properties. Although the semantics are similar, there are some stylistic conventions on when to prefer one to another.
Prefer a property over a function when the underlying algorithm:
does not throw
is cheap to calculate (or caсhed on the first run)
returns the same result over invocations if the object state hasn't changed
Platform types
A public function/method returning an expression of a platform type must declare its Kotlin type explicitly: