Kotlin (programming language)


Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of its standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Language development costs are borne by JetBrains, while the Kotlin Foundation protects the Kotlin trademark.
On 7 May 2019, Google announced that the Kotlin programming language is now its preferred language for Android app developers. 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 targets Java 6 by default, but lets the programmer choose between Java 8 to 13, for optimization.

History

In July 2011, JetBrains unveiled Project Kotlin, a new language for the JVM, which had been under development for a year. JetBrains lead Dmitry Jemerov said that most languages did not have the features they were looking for, with the exception of Scala. However, he cited the slow compilation time of Scala as a deficiency. One of the stated goals of Kotlin is to compile as quickly as Java. In February 2012, JetBrains open sourced the project under the Apache 2 license.
The name comes from Kotlin Island, near St. Petersburg. Andrey Breslav mentioned that the team decided to name it after an island just like Java was named after the Indonesian island of Java.
JetBrains hopes that the new language will drive IntelliJ IDEA sales.
Kotlin v1.0 was released on 15 February 2016. This is considered to be 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.
Kotlin v1.2 was released on 28 November 2017. Sharing code between JVM and JavaScript platforms feature was newly added to this release. Full-stack demo has been made with the new Kotlin/JS Gradle Plugin.
Kotlin v1.3 was released on 29 October 2018, bringing coroutines for asynchronous programming.
On 7 May 2019, Google announced that the Kotlin programming language is now its preferred language for Android app developers.

Design

Development lead Andrey Breslav has said that Kotlin is designed to be an industrial-strength object-oriented language, and a "better language" than Java, but still be fully interoperable with Java code, allowing companies to make a gradual migration from Java to Kotlin.
Semicolons are optional as a statement terminator; in most cases a newline is sufficient for the compiler to deduce that the statement has ended.
Kotlin variable declarations and parameter lists have the data type come after the variable name, similar to Pascal and TypeScript.
Variables in Kotlin can be read-only, declared with the keyword, or mutable, declared with the keyword.
Class members are public by default, and classes themselves are final by default, meaning that creating a derived class is disabled unless the base class is declared with the keyword.
In addition to the classes and methods of object-oriented programming, Kotlin also supports procedural programming with the use of functions.
Kotlin functions support default arguments, variable-length argument lists, named arguments and overloading by unique signature. Class member functions are virtual, i.e. dispatched based on the runtime type of the object they are called on.
Kotlin 1.3 adds support for contracts

Syntax

Procedural programming style

Kotlin relaxes Java's restriction of allowing static methods and variables to exist only within a class body. Static objects and functions can be defined at the top level of the package without needing a redundant class level. For compatibility with Java, Kotlin provides a JvmName annotation which specifies a class name used when the package is viewed from a Java project. For example, @file:JvmName.

Main entry point

As in 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.. Perl and Unix shell style string interpolation is supported. Type inference is also supported.

// Hello, World! example
fun main
fun main

Extension methods

Similar to C#, Kotlin allows a user to add methods to any class without the formalities of creating a derived class with new methods. Instead, Kotlin adds the concept of an extension method which allows a function to be "glued" onto the public method list of any class without being formally placed inside of the class. In other words, an extension method is a helper method that has access to all the public interface of a class which it can use to create a new method interface to a target class and this method will appear exactly like a method of the class, appearing as part of code completion inspection of class methods. For example:

package MyStringExtensions
fun String.lastChar: Char = get
>>> println)

By placing the preceding code in the top-level of a package, the String class is extended to include a method that was not included in the original definition of the String class.

// Overloading '+' operator using an extension method
operator fun Point.plus: Point
>>> val p1 = Point
>>> val p2 = Point
>>> println
Point

Unpack arguments with spread operator

Similar to Python, the spread operator asterisk unpacks an array's contents as comma-separated arguments to a function:

fun main

Deconstructor methods

A deconstructor's job is to decompose a class object into a tuple of elemental objects. For example, a 2D coordinate class might be deconstructed into a tuple of integer x and integer y.
For example, the collection object contains a deconstructor method that splits each collection item into an index and an element variable:

for in collection.withIndex)

Nested functions

Kotlin allows local functions to be declared inside of other functions or methods.

class User

fun saveUserToDb

Classes are final by default

In Kotlin, to derive a new class from a base class type, the base class needs to be explicitly marked as "open". This is in contrast to most object-oriented languages such as Java where classes 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
class GigaButton: MegaButton

Abstract classes are open by default

es define abstract or "Pure Virtual" placeholder function that will be defined 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

Classes are public by default

Kotlin provides the following keywords to restrict visibility for top-level declaration, such as classes, and for class members:
public, internal, protected, and private.
When applied to a class member:
public : Visible everywhere
internal: Visible in a module
protected: Visible in subclasses
private: Visible in a class
When applied to a top-level declaration
public : Visible everywhere
internal: Visible in a module
private: Visible in a file
Example:

// Class is visible only to current module
internal open class TalkativeButton : Focusable

Primary constructor vs. secondary constructors

Kotlin supports the specification of 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
//
open class PowerUser : User


However, in cases where more than one constructor is needed for a class, a more general constructor can be used called secondary constructor syntax which closely resembles the constructor syntax used in most object-oriented languages like C++, C#, and Java.

// Example of class using secondary constructor syntax
//
class MyButton : View

Data Class

Kotlin provides Data Classes to define classes that store only properties. In Java programming, classes that store only properties are not unusual, but regular classes are used for this purpose. Kotlin has given provision to exclusively define classes that store properties alone. These data classes do not have any methods but only properties. A data class does not contain a body, unlike a regular class. data keyword is used before class keyword to define a data class.

fun main

// data class with parameters and their optional default values
data class Book

Kotlin interactive shell


$ kotlinc-jvm
type :help for help; :quit for quit
>>> 2 + 2
>>> println
Hello, World!
>>>

Kotlin as a scripting language

Kotlin can also be used as a scripting language. A script is a Kotlin source file with top level executable code.

// list_folders.kts
import java.io.File
val folders = File.listFiles
folders?.forEach

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"

Complex "hello world" example


fun main
// Inline higher-order functions
inline fun greet : String = greeting andAnother s
// Infix functions, extensions, type inference, nullable types,
// lambda expressions, labeled this, Elvis operator
infix fun String.andAnother = buildString
// Immutable types, delegated properties, lazy initialization, string templates
val greeting by lazy
// Sealed classes, companion objects
sealed class to
// Extensions, Unit
fun String.print = println

Kotlin makes a distinction 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: null-check must be performed before using the value. Kotlin provides null-safe operators to help developers:

fun sayHello

An example of the use of the safe navigation operator:

// 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

Kotlin provides support for higher order functions and anonymous functions or lambdas.

// the following function takes a lambda, f, and executes f passing it the string, "lambda"
// note that -> Unit indicates a lambda with a String parameter and Unit return type
fun executeLambda

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 =
// lambdas with no parameters may simply be defined using
val l2 =

Tools

Kotlin is widely used for Android development. The platform was stuck on Java 7 for a while and Kotlin introduces many improvements for programmers such as null-pointer safety, extension functions and infix notation. Accompanied by full Java compatibility and good IDE support it is intended to improve code readability, give an easier way to extend Android SDK classes and speed up development.
Kotlin was announced as an official Android development language at Google I/O 2017. It became the third language fully supported for Android, in addition to Java and C++.

Adoption

In 2018, Kotlin was the fastest growing language on GitHub with 2.6 times more developers compared to 2017. It's the fourth most loved programming language according to the 2020 Stack Overflow Developer Survey.
Kotlin was also awarded the O'Reilly Open Source Software Conference Breakout Award for 2019.
A number of companies have publicly stated using Kotlin: