Kotlin (programming language)

from Wikipedia, the free encyclopedia
Kotlin
logo
Basic data
Paradigms : Object-oriented programming language
Publishing year: 2011 (first appearance)
2016 (stable)
Designer: JetBrains
Developer: JetBrains and open source developers
Current  version 1.4.0   (August 14, 2020)
Typing : static , strong
Influenced by: Java , Scala , C # , Groovy , Gosu , JavaScript
License : Apache 2
kotlinlang.org

Kotlin is a cross-platform , statically typed programming language , which in bytecode for the Java Virtual Machine is translated (JVM), but also in JavaScript - Source Code or (using LLVM in) machine code may be converted. Kotlin can also be used to develop Android apps and has been officially supported by Google since 2017 . Since May 2019, Kotlin has been Google's preferred language for Android app development.

development

The language is mainly developed by the Saint Petersburg- based JetBrains programmers. Hence the name: Kotlin is an island off St. Petersburg. After a year of development, in July 2011 JetBrains introduced the “Kotlin” project to the public as a new language for the JVM. In February 2012, JetBrains released the source code under an Apache 2 license . Version 1.0 of Kotlin was released on February 15, 2016. This version is considered the first official stable release.

Lead developer Dmitry Yemerov stated that most languages ​​didn't show the features they were looking for, with the exception of Scala . However, they have a slow compiler . Therefore, one of the declared goals for Kotlin was the high compile speed, as we know it from Java .

Tools

A Kotlin plug- in is available for the IDE IntelliJ IDEA , also developed by JetBrains , which can be installed since IntelliJ IDEA 15. A plug-in is also available for Eclipse . There are also plugins for Apache Maven and Gradle and a task for Apache Ant . The official Android development environment Android Studio supports Kotlin from version 3.0 as a native language for developing Android apps.

In the Java environment there are numerous frameworks and libraries that help with creating tests. Because Kotlin is fully interoperable with Java, all of these tools can be easily used to test Kotlin code.

syntax

The language is syntactically incompatible with Java, but it is designed in such a way that it can interoperate with Java code. It also uses existing code from the Java Class Library (JCL), e.g. B. the Java Collections Framework (JCF).

Unlike in Java, with Kotlin the data type of a variable is not noted in front of the variable name, but after it, separated by a colon. However, Kotlin also supports type inference , so that the type can often be omitted if it is clear from the context. A line break is sufficient to end the statement, but a semicolon can also be used as an option. In addition to classes and methods (in Kotlin: member functions ) from object-oriented programming , Kotlin supports procedural programming using functions as well as certain aspects of functional programming . As with C u. a main function .

Hello World

A program that outputs the string " Hello World ".

fun main() {                          // Einsprungpunkt (Main-Funktion)
    println("Hallo Welt!")            // Gib den String 'Hallo Welt!' aus
}

Functions

// Definition einer Funktion "funktionsBeispiel"
fun funktionsBeispiel() {
// ...
}

// Funktion mit zwei Argumenten und einem Rückgabewert
fun add(x: Int, y: Int): Int {                       
    return x + y
}

// Besteht eine Funktion aus nur einem Ausdruck, dürfen die geschweiften Klammern, der Rückgabetyp und das "return" weggelassen werden.
fun add2(x: Int, y: Int) = x + y                     

// Einsprungpunkt (Main-Funktion)
fun main(args: Array<String>) {
    // Definition einer verschachtelten Funktion, die nur in main aufgerufen werden kann.
    fun test() {
        println("Hello World!")
    }
    // Aufrufen der Funktion
    test()
}

Control flow

Kotlin supports the common control structures .

If statement

// Weist der unveränderlichen Variable 'a' den Integer-Wert 120 zu
val a = 120

// if..else-Anweisung
if (a == 100)
// Ausgabe von Text auf der Konsole
    println("a entspricht 100")
else if (a == 130)
    println("a entspricht 130")
else
    println("a entspricht weder 100 noch 130")

When statement

//  val x = 1
//  val x = 2
//  Weist der unveränderlichen Variable 'x' den Integer-Wert 5 zu
val x = 5
when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x entspricht weder 1 noch 2")
    }
}

Higher-order functions

Kotlin supports the use of higher order functions as well as closures using function pointers , anonymous functions, and lambda expressions.

// Funktion, die eine andere Funktion entgegennimmt
fun callWithInt(number: Int, fn: (Int) -> Int) {
    val result = fn(number)
    println(result)
}

// Funktion, die eine andere Funktion zurückgibt
fun makeAdder(a: Int): (Int) -> Int {
    fun add(b: Int) = a + b
    return ::add
}

// Anders als in Java dürfen in Kotlin Closures auf Variablen auch schreibend zugreifen
var number = 0
fun makeCounter(): () -> Int {
    fun counter() = ++number
    return ::counter
}

fun double(x: Int) = x * 2

fun main() {
    // Aufruf mit Funktionszeiger
    callWithInt(42, ::double)
    
    // Aufruf mit anonymer Funktion
    callWithInt(42, fun(x: Int) = x * 2)
    
    // Aufruf mit Lambda-Ausdruck
    callWithInt(42, { x -> x * 2})
    
    // Als letztes Argument dürfen Lambdas außerhalb der runden Klammern geschrieben werden.
    // Wenn die Funktion nur ein Argument erwartet, heißt dieses "it", falls nicht anders festgelegt.
    callWithInt(42) { it * 2 }
    
    val add2 = makeAdder(2)
    println(add2(5)) // gibt 7 aus
    
    val counter = makeCounter()
    println(counter()) // Gibt 1 aus
    println(counter()) // Gibt 2 aus
}

Higher-order functions are also used in the standard library, especially with collections data types such as lists, maps or sets.

val list = setOf(1, 2, 3, 4, 5)

println(list.map { it * 2 }) // [2, 4, 6, 8, 10]
println(list.filter { it > 2 }) // [3, 4, 5]
println(list.groupBy { it % 2 }) // {1=[1, 3, 5], 0=[2, 4]}

val cities = listOf("Berlin", "Hamburg", "München", "Köln", "Frankfurt")

// Die Anfangsbuchstaben der drei Städte mit den kürzesten Namen hintereinander
val result = cities
    .sortedBy { it.length }
    .take(3)
    .map { it[0] }
    .fold("") { acc, char -> acc + char }

println(result) // KBH

Zero safety

The incorrect use of null pointers , which can lead to so-called "null pointer exceptions", is a frequent cause of errors in many programming languages. Therefore, Kotlin provides a number of features that are intended to prevent such null pointer exceptions from occurring at compile time . For example, when declaring a variable, the developer must explicitly specify whether or not it can take the value zero . Variables that can be zero are called “nullable”.

// Erstellt eine Variable vom Typ "Int" (darf nicht "null" sein)
var a: Int = 123

// Erstellt eine Variable, die den Wert "null" annehmen darf.
var b: Int? = 456

// Nicht erlaubt (Erzeugt einen Kompilierfehler)
a = null

// Zugelassen
b = null

Using a variable that can become null without first checking it for null will also result in a compile-time error.

fun nullSafety() {
    val test: String? = "Test"
    
    // Kompilierfehler (könnte "Null Pointer Exception" verursachen)
    println(test.length)
    
    // Erlaubt, da auf null abgeprüft wird.
    if (test != null)
        println(test.length)
    
    // Auch erlaubt (zweite Bedingung wird nur überprüft, wenn die erste falsch ist)
    if (test == null || test.length == 0)
        println("Leerer String")
    
    // Ebenfalls erlaubt
    if (test == null)
        return
    
    println(test.length)
}

Kotlin also offers special syntax for some typical cases in order to shorten the code required.

val ort = kunde?.adresse?.ort
val ortOderLeer = ort ?: ""

// Obiger Code ist gleichbedeutend mit:

val ort: String?
if (kunde == null || kunde.adresse == null)
    ort = null
else
    ort = kunde.adresse.ort

val ortOderLeer: String
if (ort == null)
    ortOderLeer = ""
else
    ortOderLeer = ort

reception

  • Google declared Kotlin the preferred programming language for Android at the I / O 2019 developer conference.
  • In the January 2012 edition of Dr. Dobb's Journal has declared the programming language language of the month .

According to the Kotlin website , small and large projects use the language:

  • 150 million users use Pinterest every month.
  • Gradle uses Kotlin for installation scripts.
  • Evernote uses Kotlin for its Android client.
  • Uber uses Kotlin for internal tools.
  • Corda, an open source software developed entirely in Kotlin, is used by several major banks.
  • Coursera develops Android apps in part with Kotlin.
  • Atlassian uses Kotlin for the Trello tool on Android.

literature

Web links

Individual evidence

  1. Kotlin 1.4.0 .
  2. Introduction to Kotlin Programming .
  3. kotlin / license / README.md. In: JetBrains / kotlin. GitHub, accessed September 20, 2017 .
  4. Maxim Shafirov: Kotlin on Android. Now official. In: Kotlin Blog. May 17, 2017. Retrieved June 18, 2019 (American English).
  5. heise online: Google I / O: Google's commitment to Kotlin. Retrieved June 18, 2019 .
  6. ^ Sandra Upson: The Language that Stole Android Developers' Hearts. WIRED, May 19, 2017, accessed on February 23, 2018 .
  7. FAQ - Kotlin Programming Language. Retrieved February 21, 2018 .
  8. Janice Heiss: The Advent of Kotlin: A Conversation with JetBrains' Andrey Breslav . Oracle Technology Network. April 2013. Retrieved February 2, 2014.
  9. Hello World
  10. ^ A b Paul Krill: JetBrains readies JVM language Kotlin . InfoWorld. July 22, 2011. Retrieved February 2, 2014.
  11. ^ John Waters: Kotlin Goes Open Source . 1105 Enterprise Computing Group. February 22, 2012. Retrieved February 2, 2014.
  12. Andrey Breslav: Kotlin 1.0 Released: Pragmatic Language for JVM and Android . 15th February 2016.
  13. ^ What's New in IntelliJ IDEA .
  14. Kotlin plugins .
  15. Getting Started with Eclipse Neon - Kotlin Programming Language .
  16. ^ Kotlin for Eclipse .
  17. ^ Kotlin Build Tools .
  18. Rainald Menge-Sonnentag: Development environment Android Studio 3.0 speaks Kotlin . heise.de. October 26, 2017. Retrieved October 27, 2017.
  19. Kai Schmidt and Markus Schwarz: Testing with Kotlin . informatik-aktuell.de. December 17, 2019. Retrieved December 27, 2019.
  20. semicolons . Retrieved February 8, 2014.
  21. functions . Retrieved February 8, 2014.
  22. https://t3n.de/news/kotlin-google-macht-java-alternative-zur-nummer-eins-bei-der-android-app-entwicklung-1161630
  23. Andrey Breslav: Language of the Month: Kotlin . January 20, 2012. Retrieved February 2, 2014.
  24. Corda .
  25. ^ Project Kotlin .: "Kotlin in backend, data processing and service development"