Kotlin: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Zeile 15: | Zeile 15: | ||
} | } | ||
fun short() = "Hello" | fun short() = "Hello" | ||
// "named parameters": | |||
fun log(prefix: String, message: String) = println("$prefix$message") | |||
fun showNamesParams() { | |||
log(prefix:"!", message:"Hi") | |||
</pre> | </pre> | ||
Zeile 32: | Zeile 36: | ||
warn() | warn() | ||
} | } | ||
when (message) { | when (message) { | ||
null -> println("OK") | null -> println("OK") | ||
Zeile 37: | Zeile 42: | ||
} | } | ||
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.forEach { no, thing -> | |||
println(no, thing) | |||
} | |||
</pre> | |||
= Expressions = | = Expressions = | ||
<pre>name = lastName if (firstName == null) else "$firstName $lastName" | <pre>name = lastName if (firstName == null) else "$firstName $lastName" | ||
Zeile 43: | Zeile 62: | ||
else -> "$firstName $lastName" | else -> "$firstName $lastName" | ||
} | } | ||
</pre> | |||
= Typen = | |||
== String == | |||
* Konkatenation: firstName + ! " + lastName | |||
* Templates: "$firstName $lastName" | |||
== Container == | |||
<pre>val things = arrayOf("box", "books") | |||
assertTrue(things[0] == things.get(0)) | |||
</pre> | </pre> |
Version vom 17. September 2019, 09:28 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.forEach { 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
val things = arrayOf("box", "books") assertTrue(things[0] == things.get(0))