Kotlin: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
K |
|||
(13 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt) | |||
Zeile 1: | Zeile 1: | ||
Kategorie:Sprache | Kategorie:Sprache | ||
= Links = | |||
* [[Kotlin-GUI]] | |||
= Funktionen = | = Funktionen = | ||
Zeile 15: | Zeile 18: | ||
} | } | ||
fun short() = "Hello" | fun short() = "Hello" | ||
// "named parameters": | |||
fun log(prefix: String, message: String) = println("$prefix$message") | |||
fun showNamesParams() { | |||
log(prefix:"!", message:"Hi") | |||
log(message="Hi", prefix="") | |||
</pre> | |||
== Varargs == | |||
fun join(prefix: String, vararg items:String) { | |||
var rc = prefix | |||
items.foreach(items) { | |||
rc += it | |||
} | |||
return rc | |||
} | |||
== High order functions == | |||
<pre>fun printFilteredStrings(list: List<String>, predicate: (String) -> Boolean) { | |||
list.forEach { | |||
if predicate(it) { | |||
println(it) | |||
} | |||
} | |||
} | |||
fun main() { | |||
val list = listOf("a", "b"); | |||
printFilterStrings(list, { it.startswith(prefix:"J")}) | |||
} | |||
fun printFilteredStrings2(list: List<String>, (predicate: (String)?) -> Boolean) { | |||
list.forEach { | |||
if predicate?.invoke(it) == true { | |||
println(it) | |||
} | |||
} | |||
} | |||
val predicate: (String) -> Boolean = { | |||
it.startsWith(prefix:"J") | |||
} | |||
fun getPrintPredicate(): (String) -> Boolean { | |||
return { it.startsWith("J") } | |||
} | |||
</pre> | </pre> | ||
Zeile 32: | Zeile 74: | ||
warn() | warn() | ||
} | } | ||
when (message) { | when (message) { | ||
null -> println("OK") | null -> println("OK") | ||
else -> println(message) | 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.forEachIndexed { no, thing -> | |||
println(no, thing) | |||
} | |||
</pre> | |||
= Expressions = | = Expressions = | ||
Zeile 42: | Zeile 100: | ||
null -> lastName | null -> lastName | ||
else -> "$firstName $lastName" | else -> "$firstName $lastName" | ||
} | |||
// Ersatz, wenn null | |||
name += lastName :? "" | |||
</pre> | |||
= Typen = | |||
* if item is Person { ... } | |||
* if item !is Person { ... } | |||
* Cast: (infoProvider as SessionInfoProvider).getSessionId() | |||
== String == | |||
* Konkatenation: firstName + ! " + lastName | |||
* Templates: "$firstName $lastName" | |||
== Enums == | |||
<pre>enum class EntityType { | |||
EASY, MEDIUM, HARD: | |||
fun formated() = name.toLowerCase() | |||
} | |||
when type { | |||
EntityType.EASY -> type.name // Metainfo | |||
else -> "not easy" | |||
} | |||
</pre> | |||
== Container == | |||
* Normalerweise: nicht änderbar ("immutable") | |||
* List<String> | |||
* MutableList<Int> | |||
<pre>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. | |||
</pre> | |||
= Klassen = | |||
* Klassen: private / internal | |||
* Members: private / protected | |||
* Klassen + vals: open: kann abgeleitet werden | |||
** in abgeleiteter Klasse: override | |||
<pre>class Person constructor() | |||
class Person(_firstName: String, lastName: String){ | |||
val age: Int? = null | |||
val firstName: String | |||
val lastName: String | |||
init { | |||
firstName = _firstName | |||
lastName = _lastName | |||
} | |||
} | |||
// Kürzer: | |||
class Person(val firstName: String, val lastName: String){ | |||
// 2.ter Konstruktor: | |||
constructor(): this("Peter", "Parker") | |||
var nickName: String? = null | |||
// expliziter Setter: | |||
set(value){ | |||
println("nickname is set") | |||
field = value | |||
} | |||
get() { | |||
println("access to nickname") | |||
return field | |||
} | |||
} | |||
open class BasicInfoProvider { | |||
} | |||
class FancyInfoProvider : BasicInfoProvider { | |||
} | |||
</pre> | |||
== sealed class == | |||
<pre>sealed class Entity { | |||
data class Easy(val id: String, val name: String): Entity | |||
data class Hard(val id: String, val name: String, multiplyer:Float): Entity | |||
} | |||
entity = Entity.Easy("x", "Jones") | |||
</pre> | |||
== extended functions == | |||
* Beliebige Klasse (ohne Sourcecode) erweitern: | |||
<pre>fun String.printInfo() { | |||
.. | |||
} | |||
val Entity.Medium.info: String | |||
get() = "some info" | |||
</pre> | |||
== Companion object == | |||
<pre> class Entity private constructor(val id: String) { | |||
compianion Factory { | |||
const val id = "id" | |||
fun create() = Entitiy(id) | |||
} | |||
} | |||
fun main() { | |||
val entity = Entity.Factory.create() | |||
} | |||
</pre> | |||
= Interfaces = | |||
<pre>interface personInfoProvider { | |||
fun printInfo(person: Person) | |||
fun debug(person: Person) { | |||
person.debug() | |||
} | |||
val providerInfo: String | |||
} | |||
class BasicInfoProvider: PersonInfoProvider { | |||
override val providerInfo = "!" | |||
override fun printInfo(person: Person) { | |||
super.printInfo(person) | |||
} | |||
} | |||
</pre> | |||
= Funktionale Programmierung = | |||
<pre>fun main(){ | |||
val list = listOf("Kotlin", "Java", "JS", "C++") | |||
list | |||
.filterNotNull() | |||
.take(n:3) | |||
.takeLast(n:1) | |||
.find { it.startsWith("J") } | |||
.findLast { it.startsWith("X") }.orEmpty() | |||
.associate { it to it.length() } | |||
.filter { | |||
it.startsWith("J") | |||
} | |||
.forEach { | |||
println(it) | |||
} | |||
list | |||
.associate { it to it.length() } | |||
.forEach { | |||
println("${it.value}, ${it.key}") | |||
} | |||
val map = list | |||
.filterNotNull() | |||
.associate { it to it.length() } | |||
// Letztes Element einer Liste ist null: | |||
val last = list.filterNotNull().last() | |||
} | } | ||
</pre> | </pre> |
Aktuelle Version vom 17. September 2019, 11:48 Uhr
Kategorie:Sprache
Links[Bearbeiten]
Funktionen[Bearbeiten]
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") log(message="Hi", prefix="")
Varargs[Bearbeiten]
fun join(prefix: String, vararg items:String) {
var rc = prefix items.foreach(items) { rc += it } return rc
}
High order functions[Bearbeiten]
fun printFilteredStrings(list: List<String>, predicate: (String) -> Boolean) { list.forEach { if predicate(it) { println(it) } } } fun main() { val list = listOf("a", "b"); printFilterStrings(list, { it.startswith(prefix:"J")}) } fun printFilteredStrings2(list: List<String>, (predicate: (String)?) -> Boolean) { list.forEach { if predicate?.invoke(it) == true { println(it) } } } val predicate: (String) -> Boolean = { it.startsWith(prefix:"J") } fun getPrintPredicate(): (String) -> Boolean { return { it.startsWith("J") } }
Values/Variables[Bearbeiten]
- Top-Level-Variable (außerhalb Klassen/Funktionen)
- val name: String = "default" // readonly
- var name: String
- Typinferenz (automatischer Typ): var name = "Adam"
Nullable Types[Bearbeiten]
- var name?: String = null
- String-Variables, die mit Typinferenz definiert sind, sind Nullable.
Statements[Bearbeiten]
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.forEachIndexed { no, thing -> println(no, thing) }
Expressions[Bearbeiten]
name = lastName if (firstName == null) else "$firstName $lastName" name = lastName when(firstName) { null -> lastName else -> "$firstName $lastName" } // Ersatz, wenn null name += lastName :? ""
Typen[Bearbeiten]
- if item is Person { ... }
- if item !is Person { ... }
- Cast: (infoProvider as SessionInfoProvider).getSessionId()
String[Bearbeiten]
- Konkatenation: firstName + ! " + lastName
- Templates: "$firstName $lastName"
Enums[Bearbeiten]
enum class EntityType { EASY, MEDIUM, HARD: fun formated() = name.toLowerCase() } when type { EntityType.EASY -> type.name // Metainfo else -> "not easy" }
Container[Bearbeiten]
- 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.
Klassen[Bearbeiten]
- Klassen: private / internal
- Members: private / protected
- Klassen + vals: open: kann abgeleitet werden
- in abgeleiteter Klasse: override
class Person constructor() class Person(_firstName: String, lastName: String){ val age: Int? = null val firstName: String val lastName: String init { firstName = _firstName lastName = _lastName } } // Kürzer: class Person(val firstName: String, val lastName: String){ // 2.ter Konstruktor: constructor(): this("Peter", "Parker") var nickName: String? = null // expliziter Setter: set(value){ println("nickname is set") field = value } get() { println("access to nickname") return field } } open class BasicInfoProvider { } class FancyInfoProvider : BasicInfoProvider { }
sealed class[Bearbeiten]
sealed class Entity { data class Easy(val id: String, val name: String): Entity data class Hard(val id: String, val name: String, multiplyer:Float): Entity } entity = Entity.Easy("x", "Jones")
extended functions[Bearbeiten]
- Beliebige Klasse (ohne Sourcecode) erweitern:
fun String.printInfo() { .. } val Entity.Medium.info: String get() = "some info"
Companion object[Bearbeiten]
class Entity private constructor(val id: String) { compianion Factory { const val id = "id" fun create() = Entitiy(id) } } fun main() { val entity = Entity.Factory.create() }
Interfaces[Bearbeiten]
interface personInfoProvider { fun printInfo(person: Person) fun debug(person: Person) { person.debug() } val providerInfo: String } class BasicInfoProvider: PersonInfoProvider { override val providerInfo = "!" override fun printInfo(person: Person) { super.printInfo(person) } }
Funktionale Programmierung[Bearbeiten]
fun main(){ val list = listOf("Kotlin", "Java", "JS", "C++") list .filterNotNull() .take(n:3) .takeLast(n:1) .find { it.startsWith("J") } .findLast { it.startsWith("X") }.orEmpty() .associate { it to it.length() } .filter { it.startsWith("J") } .forEach { println(it) } list .associate { it to it.length() } .forEach { println("${it.value}, ${it.key}") } val map = list .filterNotNull() .associate { it to it.length() } // Letztes Element einer Liste ist null: val last = list.filterNotNull().last() }