Kotlin: Unterschied zwischen den Versionen

Aus Info-Theke
Zur Navigation springen Zur Suche springen
K
 
(11 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt)
Zeile 1: Zeile 1:
Kategorie:Sprache
Kategorie:Sprache
= Links =
* [[Kotlin-GUI]]


= Funktionen =
= Funktionen =
Zeile 19: Zeile 22:
fun showNamesParams() {
fun showNamesParams() {
   log(prefix:"!", message:"Hi")
   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 52: Zeile 90:
   println(thing)
   println(thing)
}
}
things.forIndexedEach { no, thing ->
things.forEachIndexed { no, thing ->
   println(no, thing)
   println(no, thing)
}
}
</pre>
</pre>
= Expressions =
= Expressions =
<pre>name = lastName if (firstName == null) else "$firstName $lastName"
<pre>name = lastName if (firstName == null) else "$firstName $lastName"
Zeile 62: Zeile 101:
   else -> "$firstName $lastName"
   else -> "$firstName $lastName"
}
}
// Ersatz, wenn null
name += lastName :? ""
</pre>
</pre>


= Typen =
= Typen =
* if item is Person { ... }
* if item !is Person { ... }
* Cast: (infoProvider as SessionInfoProvider).getSessionId()
== String ==
== String ==
* Konkatenation: firstName + ! " + lastName
* Konkatenation: firstName + ! " + lastName
* Templates: "$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 ==
== Container ==
Zeile 79: Zeile 134:
val map = mutableMapOf(1 to "a", 2 to "b", 3 to "c")
val map = mutableMapOf(1 to "a", 2 to "b", 3 to "c")
map.
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()
}