Kotlin
General-purpose programming language derived from Java
From Wikipedia, the free encyclopedia
Kotlin (/ˈkɒtlɪn/)[3] is a cross-platform, statically typed, general-purpose high-level programming language with type inference. Kotlin is designed to interoperate fully with Java, and the Java virtual machine (JVM) version of Kotlin's standard library depends on the Java Class Library. However, type inference allows for more concise syntax. Kotlin mainly targets the JVM, but also compiles to JavaScript (e.g., for frontend web applications using React)[4] or native code via LLVM (e.g., for native iOS apps sharing business logic with Android apps).[5] JetBrains bears language development costs, while the Kotlin Foundation protects the Kotlin trademark.[6]
| Kotlin | |
|---|---|
| Paradigms | Multi-paradigm: object-oriented, functional, imperative, block structured, generic, reflective, concurrent |
| Designed by | JetBrains |
| Developer | JetBrains |
| First appeared | 22 July 2011 |
| Stable release | |
| Typing discipline | Inferred, static, strong |
| Platform |
|
| OS | Cross-platform |
| License | Apache 2.0 |
| Filename extensions | .kt, .kts, .kexe, .klib |
| Website | kotlinlang |
| Influenced by | |
| Influenced | |
| V (Vlang) | |
On 7 May 2019, Google announced Kotlin had become its preferred language for Android app developers.[7] Since the release of Android Studio 3.0 in October 2017, Kotlin has been included as an alternative to the standard Java compiler. The Android Kotlin compiler emits Java 8 bytecode by default (which runs in any later JVM), but allows targeting Java 9 up to 24,[8] for optimizing, or allows for more features; it has bidirectional record class interoperability support for JVM, introduced in Java 16, considered stable as of Kotlin 1.5.
Kotlin has support for the web with Kotlin/JS, through an intermediate representation-based backend that has been declared stable since version 1.8, released in December 2022. Kotlin/Native (e.g., Apple silicon support) has been declared stable since version 1.9.20, released in November 2023.[9][10]
History


Name
The name is derived from Kotlin Island, a Russian island in the Gulf of Finland, near Saint Petersburg. Andrey Breslav, Kotlin's former lead designer, mentioned that the team decided to name it after an island, in imitation of the Java programming language, which shares a name with the Indonesian island of Java.[11]
Development
The first commit to the Kotlin Git repository was on 8 November 2010.[12]
In July 2011, JetBrains unveiled Project Kotlin, a new JVM language that had been under development for a year.[13] JetBrains lead Dmitry Jemerov said that most languages lacked the features they were looking for, except for Scala. However, he cited Scala's slow compilation time as a deficiency.[13] One of Kotlin's stated goals is to compile as quickly as Java. In February 2012, JetBrains open-sourced the project under the Apache 2 license.[14]
JetBrains expected Kotlin to drive sales of IntelliJ IDEA.[15]
Kotlin 1.0 was released on 15 February 2016,[16] which is considered the first officially stable release, and JetBrains has committed to long-term backwards compatibility starting with this version.
At Google I/O 2017, Google announced first-class support for Kotlin on Android.[17] On 7 May 2019, Google announced that Kotlin is now its preferred language for Android app developers.[7]
Design
Development lead Andrey Breslav has said that Kotlin is designed to be an industrial-strength object-oriented language, a "better language" than Java, and still fully interoperable with Java code, allowing companies to make a gradual migration from Java to Kotlin.[18]
Semicolons are optional as a statement terminator; in most cases, a newline is sufficient for the compiler to deduce that the statement has ended.[19]
Kotlin variable declarations and parameter lists place the data type after the variable name (separated by a colon), similar to Ada, BASIC, Pascal, TypeScript, and Rust. This, according to an article from Roman Elizarov, current project lead, results in alignment of variable names and is more pleasing to the eyes, especially when there are a few variable declarations in succession, and one or more of the types are too complex for type inference, or need to be declared explicitly for human readers to understand.[20][21]
The influence of Scala in Kotlin can be seen in the extensive support for both object-oriented and functional programming[22] and in several specific features:
- There is a distinction between mutable and immutable variables (var vs val keyword)
- All classes are public and final (non-inheritable) by default
- Functions and methods support default arguments, variable-length argument lists, and named arguments
Kotlin 1.3 added support for contracts,[23] which are stable for the standard library declarations, but still experimental for user-defined declarations. Contracts are inspired by the design-by-contract[24] programming paradigm.
Like Scala.js, Kotlin code can be transpiled to JavaScript, enabling interoperability between Kotlin and JavaScript and allowing either writing complete web applications in Kotlin or sharing code between a Kotlin backend and a JavaScript frontend.[25]
Syntax
Procedural programming style
Kotlin relaxes the Java restriction on static methods and variables, allowing them to exist outside a class body. Static objects and functions can be defined at the top level of the package without requiring a redundant class-level scope. For compatibility with Java, Kotlin provides the JvmName annotation, which specifies the class name used when the package is viewed from a Java project. For example, @file:JvmName("JavaClassName").
Main entry point
As in C, C++, C#, Java, and Go, the entry point to a Kotlin program is a function named main, which may be passed an array containing any command-line arguments. This is optional since Kotlin 1.3.[26] Perl, PHP, and Unix shell–style string interpolation is supported. Type inference is also supported.
// Hello, World! example
fun main() {
val scope = "World"
println("Hello, $scope!")
}
fun main(args: Array<String>) {
for (arg in args) {
println(arg)
}
}
Extension functions
Similar to C#, Kotlin allows adding an extension function to any class without the formalities of creating a derived class with new functions. An extension function has access to all the public interface of a class, which it can use to create a new function interface to a target class. An extension function will appear exactly like a class function and will be shown in code completion inspections of class functions. For example:
package org.wikipedia.examples
fun String.lastChar(): Char = get(length - 1)
println("Kotlin".lastChar()) // prints: n
By placing the preceding code in the top-level of a package, the String class is extended to include a lastChar function that was not included in the original definition of the String class.
// Overloading '+' operator using an extension function
operator fun Point.plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
val p1 = Point(10, 20)
val p2 = Point(30, 40)
println(p1 + p2) // prints: Point(x=40, y=60)
Scope functions
Kotlin has five scope functions that allow changing the scope within the context of an object. The scope functions are let, run, with, apply, and also.[27]
Unpack arguments with the spread operator
Similar to Python, the spread operator asterisk (*) unpacks an array's contents as individual arguments to a function, e.g.:
fun main(args: Array<String>) {
val list: List<String> = listOf("args: ", *args)
println(list)
}
Destructuring declarations
Destructuring declarations decompose an object into multiple variables at once, e.g., a 2D coordinate object might be destructured into two integers, x and y.
For example, the Map.Entry object supports destructuring to simplify access to its key and value fields:
for ((key, value) in map) {
println("$key: $value")
}
Nested functions
Kotlin allows local functions to be declared inside other functions or methods.
class User(val id: Int, val name: String, val address: String)
fun saveUserToDb(user: User) {
fun validate(user: User, value: String, fieldName: String) {
require(value.isNotEmpty()) {
"Can't save user ${user.id}: empty $fieldName"
}
}
validate(user, user.name, "Name")
validate(user, user.address, "Address")
// Save user to the database
// ...
}
Classes are final by default
In Kotlin, to derive a new class from a base class, the base class must be explicitly marked as open; in contrast, most object-oriented languages, such as Java, are open by default.
Example of a base class that is open to deriving a new subclass from it:
// open on the class means this class will allow derived classes
open class MegaButton {
// no-open on a function means that
// polymorphic behavior disabled if function overridden in derived class
fun disable() {
// ...
}
// open on a function means that
// polymorphic behavior allowed if function is overridden in derived class
open fun animate() {
// ...
}
}
class GigaButton: MegaButton() {
// Explicit use of override keyword required to override a function in derived class
override fun animate() {
println("Giga Click!")
}
}
Abstract classes are open by default
Abstract classes define abstract, or "pure virtual", placeholder functions that will be implemented in a derived class. Abstract classes are open by default.
// No need for the open keyword here, it's already open by default
abstract class Animated {
// This virtual function is already open by default as well
abstract fun animate()
open fun stopAnimating() {
// ...
}
fun animateTwice() {
// ...
}
}
Classes are public by default
Kotlin provides the following keywords to restrict visibility for top-level declarations (such as classes) and for class members: public, internal, protected, and private.
When applied to a class member:
| Keyword | Visibility |
|---|---|
public (default) | Everywhere |
internal | Within a module |
protected | Within subclasses |
private | Within a class |
When applied to a top-level declaration:
| Keyword | Visibility |
|---|---|
public (default) | Everywhere |
internal | Within a module |
private | Within a file |
Example:
// Class is visible only to current module
internal open class TalkativeButton {
// method is only visible to current class
private fun yell() = println("Hey!")
// method is visible to current class and derived classes
protected fun whisper() = println("Let's talk!")
}
internal class MyTalkativeButton: TalkativeButton() {
fun utter() = super.whisper()
}
MyTalkativeButton().utter()
Primary constructor vs. secondary constructors
Kotlin supports specifying a "primary constructor" as part of the class definition itself, consisting of an argument list following the class name. This argument list supports an expanded syntax on Kotlin's standard function argument lists that enables declaration of class properties in the primary constructor, including visibility, extensibility, and mutability attributes. Additionally, when defining a subclass, properties in super-interfaces and super-classes can be overridden in the primary constructor.
// Example of class using primary constructor syntax
// (Only one constructor required for this class)
open class BaseUser(open var isSubscribed: Boolean)
open class PowerUser(protected val nickname: String, final override var isSubscribed: Boolean = true):BaseUser(isSubscribed) { }
However, when more than one constructor is needed for a class, a more general constructor can be defined using secondary constructor syntax, which closely resembles that of most object-oriented languages such as C++, C#, and Java.
// Example of class using secondary constructor syntax
// (more than one constructor required for this class)
class Context
class AttributeSet
open class View(ctx:Context) {
constructor(ctx: Context, attr: AttributeSet): this(ctx)
}
class MyButton : View {
// Constructor #1
constructor(ctx: Context) : super(ctx) {
// ...
}
// Constructor #2
constructor(ctx: Context, attr: AttributeSet) : super(ctx, attr) {
// ...
}
}
Sealed classes
Sealed classes and interfaces restrict subclass hierarchies, meaning more control over the inheritance hierarchy.
Declaration of sealed interface and class:
sealed interface Expr
sealed class Job
All the subclasses of the sealed class are defined at compile time. No new subclasses can be added to it after the module containing the sealed class is compiled. For example, a sealed class in a compiled jar file cannot be subclassed.
sealed class Vehicle
data class Car(val brandName: String, val owner: String, val color: String): Vehicle()
class Bike(val brandName: String, val owner: String, val color: String): Vehicle()
class Tractor(val brandName: String, val owner: String, val color: String): Vehicle()
val kiaCar = Car("KIA", "John", "Blue")
val hyundaiCar = Car("Hyundai", "Britto", "Green")
Data classes
Kotlin's data class construct defines classes whose primary purpose is storing data, similar to Java's record types. Like Java's record types, the construct is similar to a regular class, except that the key methods equals, hashCode, and toString are automatically generated from the class's properties. Unlike Java's records, data classes are open for inheritance.
Kotlin interactive shell
$ kotlinc-jvm
type :help for help; :quit for quit
>>> 2 + 2
4
>>> println("Hello, World!")
Hello, World!
Kotlin as a scripting language
Kotlin can also be used as a scripting language. A script is a Kotlin source file using the .kts filename extension, with executable source code at the top-level scope:
// list_folders.kts
import java.io.File
val folders = File(args[0]).listFiles { file -> file.isDirectory() }
folders?.forEach(::println)
Scripts can be run by passing the -script option and the corresponding script file to the compiler.
$ kotlinc -script list_folders.kts "path_to_folder_to_inspect"
Null safety
Kotlin distinguishes between nullable and non-nullable data types. All nullable objects must be declared with a "?" postfix after the type name. Operations on nullable objects need special care from developers: a null-check must be performed before using the value, either explicitly, or with the aid of Kotlin's null-safe operators:
- ?. (the safe navigation operator) can be used to safely access a method or property of a possibly null object. If the object is null, the method will not be called, and the expression evaluates to null. Example:
// returns null if... // - foo() returns null, // - or if foo() is non-null, but bar() returns null, // - or if foo() and bar() are non-null, but baz() returns null. // vice versa, return value is non-null if and only if foo(), bar() and baz() are non-null foo()?.bar()?.baz()
- ?: (the null coalescing operator) is a binary operator that returns the first operand, if non-null, else the second operand. It is often referred to as the Elvis operator, due to its resemblance to an emoticon representation of Elvis Presley.
fun sayHello(maybe: String?, neverNull: Int) { // use of Elvis operator val name: String = maybe ?: "stranger" println("Hello $name") }
Lambdas
Kotlin supports higher-order functions and anonymous functions, or lambdas.[28]
// the following function takes a lambda, f, and executes f passing it the string "lambda"
// note that (String) -> Unit indicates a lambda with a String parameter and Unit return type
fun executeLambda(f: (String) -> Unit) {
f("lambda")
}
Lambdas are declared using braces, { }. If a lambda takes parameters, they are declared within the braces and followed by the -> operator.
// the following statement defines a lambda that takes a single parameter and passes it to the println function
val l = { c : Any? -> println(c) }
// lambdas with no parameters may simply be defined using { }
val l2 = { print("no parameters") }
"Hello world" example
(Taken from and explained at https://kotlinlang.org/docs/kotlin-tour-hello-world.html.)
fun main() {
println("Hello, world!")
// Hello, world!
}
Tools
- Android Studio (based on IntelliJ IDEA) has official support for Kotlin since Android Studio 3.[29]
- Integration with common Java build tools is supported, including Apache Maven,[30] Apache Ant,[31] and Gradle.[32]
- Emacs has a Kotlin Mode in its MELPA package repository.
- JetBrains also provides a plugin for Eclipse.[33][34]
- IntelliJ IDEA has plugin-based support for Kotlin.[35] IntelliJ IDEA 15 was the first version to bundle the Kotlin plugin in the IntelliJ Installer and to provide Kotlin support out of the box.[36]
- Gradle: Kotlin integrates seamlessly with Gradle, a build automation tool.[37]
Kotlin Multiplatform
Kotlin Multiplatform enables a single codebase to target multiple platforms, including Windows, Linux, the web, Android, and iOS.[38][39]
Compose Multiplatform is a multiplatform UI framework based on Jetpack Compose. It is Jetpack Compose for Android ported to Windows, macOS, Linux, web, and iOS.[40][41][42] Jetpack Compose uses a Kotlin compiler plugin to transform composable functions into UI elements.[43] For example, the Text composable function displays a text label on the screen.
Applications
When Kotlin was announced as an official Android development language at Google I/O in May 2017, it became the third language fully supported for Android, after Java and C++.[44] As of 2020[update], Kotlin was the most widely used language on Android, with Google estimating that 70% of the top 1,000 apps on the Play Store were written in Kotlin. Google itself had 60 apps written in Kotlin, including Maps and Drive. Many Android apps, such as Google Home, were in the process of migrating to Kotlin and therefore use both Kotlin and Java. Kotlin on Android is seen as beneficial for its null-safety and features that make code shorter and more readable.[45]
Ktor is a JetBrains Kotlin-first framework for building server and client applications.[46][47] The Spring Framework officially added Kotlin support with version 5, on 4 January 2017.[48] To further support Kotlin, Spring has translated all its documentation into Kotlin and added built-in support for many Kotlin-specific features, such as coroutines.[49]
In 2020, JetBrains found in a survey of developers who use Kotlin that 56% used it for mobile apps, while 47% used it for a web backend. Just over a third of all Kotlin developers said they were migrating from another language. Most Kotlin users targeted Android (or the JVM), with only 6% using Kotlin Native.[50]
Adoption
In 2018, Kotlin was the fastest-growing language on GitHub, with 2.6 times as many developers as in 2017.[51] It is the fourth-most-loved programming language according to the 2020 Stack Overflow Developer Survey.[52]
Kotlin was also awarded the O'Reilly Open Source Software Conference Breakout Award for 2019.[53]
Many companies/organizations have used Kotlin for backend development:
- Allegro[54]
- Amazon[55]
- Atlassian[56]
- Cash App[57][58]
- Flux[59]
- Google[60]
- Gradle[61]
- JetBrains[62]
- Meshcloud[63]
- Norwegian Tax Administration[64]
- OLX[65]
- Pivotal[66]
- Rocket Travel[67]
- Shazam[68]
- Zalando[69]
Some companies/organizations have used Kotlin for web development:
Several companies have publicly stated they were using Kotlin:
- Basecamp[74]
- Corda, a distributed ledger developed by a consortium of well-known banks (such as Goldman Sachs, Wells Fargo, J.P. Morgan, Deutsche Bank, UBS, HSBC, BNP Paribas, and Société Générale), has over 90% of its codebase written in Kotlin.[citation needed]
- Coursera[75]
- DripStat[76]
- Duolingo[77]
- Meta[78]
- Netflix[79]
- Pinterest[80]
- Trello[81]
- Uber[82]