Kotlin: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Zeile 52: | Zeile 52: | ||
println(thing) | println(thing) | ||
} | } | ||
things. | things.forIndexedEach { no, thing -> | ||
println(no, thing) | println(no, thing) | ||
} | } | ||
Zeile 70: | Zeile 70: | ||
== Container == | == Container == | ||
* Normalerweise: nicht änderbar ("immutable") | |||
* List<String> | |||
* MutableList<Int> | |||
<pre>val things = arrayOf("box", "books") | <pre>val things = arrayOf("box", "books") | ||
assertTrue(things[0] == things.get(0)) | assertTrue(things[0] == things.get(0)) | ||
val map = mapOf(1 to "a", 2 to "b", 3 to "c") | |||
map.forEach { key, value -> println("$key -> $value") } | |||
val map = mutableMapOf(1 to "a", 2 to "b", 3 to "c") | |||
map. | |||
</pre> | </pre> |
Version vom 17. September 2019, 09:36 Uhr
Kategorie:Sprache
Funktionen
fun main() { println(getGreetings()) } # Statt void: Unit fun log(message?: String): Unit { if message != null { println(message) } } fun getGreetings(): String { return "Hi" } fun short() = "Hello" // "named parameters": fun log(prefix: String, message: String) = println("$prefix$message") fun showNamesParams() { log(prefix:"!", message:"Hi")
Values/Variables
- Top-Level-Variable (außerhalb Klassen/Funktionen)
- val name: String = "default" // readonly
- var name: String
- Typinferenz (automatischer Typ): var name = "Adam"
Nullable Types
- var name?: String = null
- String-Variables, die mit Typinferenz definiert sind, sind Nullable.
Statements
if isTrue(condition) { doIt() } else { warn() } when (message) { null -> println("OK") else -> println(message) } for thing in arrayOf("a", "b") { } // Gleich: things.forEach { println(it) // "it" ist aktueller Wert } // Gleich: things.forEach { thing -> // "thing" ist aktueller Wert println(thing) } things.forIndexedEach { no, thing -> println(no, thing) }
Expressions
name = lastName if (firstName == null) else "$firstName $lastName" name = lastName when(firstName) { null -> lastName else -> "$firstName $lastName" }
Typen
String
- Konkatenation: firstName + ! " + lastName
- Templates: "$firstName $lastName"
Container
- Normalerweise: nicht änderbar ("immutable")
- List<String>
- MutableList<Int>
val things = arrayOf("box", "books") assertTrue(things[0] == things.get(0)) val map = mapOf(1 to "a", 2 to "b", 3 to "c") map.forEach { key, value -> println("$key -> $value") } val map = mutableMapOf(1 to "a", 2 to "b", 3 to "c") map.