Open main menu

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,[2] but type inference allows its syntax to be more concise. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code (via LLVM). Kotlin is sponsored by JetBrains and Google through the Kotlin Foundation.

Kotlin
Kotlin-logo.svg
Designed byJetBrains
DeveloperJetBrains and open-source contributors
First appeared2011
Stable release
1.3.31 / April 25, 2019; 48 days ago (2019-04-25)[1]
Typing disciplineInferred, static, strong
PlatformJVM, JavaScript, LLVM
OSCross-platform
LicenseApache License 2.0
Filename extensions
  • .kt
  • .kts
Websitekotlinlang.org
Influenced by

Kotlin is officially supported by Google for mobile development on Android.[3] Since the release of Android Studio 3.0 in October 2017, Kotlin is included as an alternative to the standard Java compiler. The Android Kotlin compiler lets the user choose between targeting Java 6 or Java 8 compatible bytecode.[4]

Kotlin has been Google’s preferred language for Android app development since May 7th, 2019.[5]

Contents

HistoryEdit

In July 2011, JetBrains unveiled Project Kotlin, a new language for the JVM, which had been under development for a year.[6] 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.[6] 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.[7]

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[8] (though the programming language Java was perhaps named after the coffee).[9]

JetBrains hopes that the new language will drive IntelliJ IDEA sales.[10]

Kotlin v1.0 was released on February 15, 2016.[11] 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.[3]

Kotlin v1.2 was released on November 28, 2017.[12] Sharing code between JVM and Javascript platforms feature was newly added to this release.

Kotlin v1.3 was released on October 29, 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.

DesignEdit

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.[13]

Semicolons are optional as a statement terminator; in most cases a newline is sufficient for the compiler to deduce that the statement has ended.[14]

Kotlin variable declarations and parameter lists have the data type come after the variable name (and with a colon separator), similar to Pascal.

Variables in Kotlin can be immutable, declared with the val keyword, or mutable, declared with the var keyword.[15]

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 open keyword.

In addition to the classes and methods (called member functions in Kotlin) of object-oriented programming, Kotlin also supports procedural programming with the use of functions.[16]

Kotlin functions (and constructors) 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.

SyntaxEdit

Functional programming styleEdit

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("JavaClassName").

Main entry pointEdit

As in C and C++, 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[17]). Perl and Unix shell style string interpolation is supported. Type inference is also supported.

 1 // Hello, World! example
 2 fun main() {
 3   val scope = "World"
 4   println("Hello, $scope!")
 5 }
 6 
 7 fun main(args: Array<String>) {
 8   for (arg in args) {
 9     println(arg)
10   }
11 }

Extension methodsEdit

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:

1 package MyStringExtensions
2 
3 fun String.lastChar(): Char = get(length - 1)
4 
5 >>> println("Kotlin".lastChar())

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

1 // Overloading '+' operator using an extension method
2 operator fun Point.plus(other: Point): Point {
3     return Point(x + other.x, y + other.y)
4 }
5 
6 >>> val p1 = Point(10, 20)
7 >>> val p2 = Point(30, 40)
8 >>> println(p1 + p2)
9 Point(x=40, y=60)

Unpack arguments with spread operatorEdit

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

1 fun main(args: Array<String>) { 
2     val list = listOf("args: ", *args)
3     println(list)
4 }

Deconstructor methodsEdit

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:

1 for ((index, element) in collection.withIndex()) { 
2      println("$index: $element")
3 }

Nested functionsEdit

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

 1 class User(val id: Int, val name: String, val address: String)
 2     
 3 fun saveUserToDb(user: User) {
 4     fun validate(user: User, value: String, fieldName: String) {
 5         if (value.isEmpty()) {
 6             throw IllegalArgumentException("Can't save user ${user.id}: empty $fieldName")
 7         }
 8     }
 9     
10     validate(user, user.name, "Name") 
11     validate(user, user.address, "Address")
12     // Save user to the database 
13     ...
14 }

Classes are final by defaultEdit

In Kotlin if you want to derive a new class from a base class type, then this base class needs to be explicitly marked as "open" in order to allow this to happen. 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.

 1 // open on the class means this class will allow derived classes
 2 open class MegaButton  {
 3 
 4     // no-open on a function means that 
 5     //    polymorphic behavior disabled if function overridden in derived class
 6     fun disable() { ... }
 7 
 8     // open on a function means that
 9     //    polymorphic behavior allowed if function is overridden in derived class
10     open fun animate() { ... }
11 }
12 
13 class GigaButton: MegaButton {
14 
15     // Explicit use of override keyword required to override a function in derived class
16     override fun animate() { println("Giga Click!") } 
17 }

Abstract classes are open by defaultEdit

Abstract classes define abstract or "Pure Virtual" placeholder function that will be defined in a derived class. Abstract classes are open by default.

 1 // No need for the open keyword here, it’s already open by default
 2 abstract class Animated {
 3 
 4     // This virtual function is already open by default as well
 5     abstract fun animate()
 6   
 7     open fun stopAnimating() { }
 8 
 9     fun animateTwice() { }
10 }

Classes are public by defaultEdit

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 (default): Visible everywhere 
   internal:         Visible in a module 
   protected:        Visible in subclasses 
   private:          Visible in a class

When applied to a top-level declaration

   public (default):  Visible everywhere
   internal:          Visible in a module
   private:           Visible in a file

Example:

1 // Class is visible only to current module
2 internal open class TalkativeButton : Focusable {
3     // method is only visible to current class 
4     private   fun yell() = println("Hey!")
5 
6     // method is visible to current class and derived classes
7     protected fun whisper() = println("Let's talk!")
8 }

Primary constructor vs. secondary constructorsEdit

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.

1 // Example of class using primary constructor syntax
2 // (Only one constructor required for this class)
3 open class PowerUser : User (
4     protected val nickname: String, 
5     final override var isSubscribed: Boolean = true) 
6     {
7          ...
8     }

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.

 1 // Example of class using secondary constructor syntax
 2 // (more than one constructor required for this class)
 3 class MyButton : View {
 4 
 5     // Constructor #1 
 6     constructor(ctx: Context) : super(ctx) { 
 7         // ... 
 8     } 
 9   
10     // Constructor #2
11     constructor(ctx: Context, attr: AttributeSet) : super(ctx, attr) { 
12         // ... 
13     }
14 }

Data ClassEdit

Kotlin provides Data Classes to define classes that store only properties. In Java programming, classes that store only properties aren't 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.

1 fun main(args: Array) {
2     // create a data class object like any other class object
3     var book1 = Book("Kotlin Programming",250)
4     println(book)
5     // output: Book(name=Kotlin Programming, price=250)
6 }
7      
8 // data class with parameters and their optional default values
9 data class Book(val name: String = "", val price: Int = 0)

Anko libraryEdit

Anko is a library specifically created for Kotlin to help build Android UI applications.[18]

1     fun Activity.showAreYouSureAlert(process: () -> Unit) {
2         alert(
3             title   = "Are you sure?",
4             message = "Are you really sure?") 
5             {
6               positiveButton("Yes") { process() }
7               negativeButton("No") { cancel() }
8             }
9     }

Kotlin interactive shellEdit

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

Kotlin as a scripting languageEdit

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

1 // list_folders.kts
2 import java.io.File
3 val folders = File(args[0]).listFiles { file -> file.isDirectory() }
4 folders?.forEach { folder -> println(folder) }

To run a script, you pass the -script option to the compiler with the corresponding script file:

1 $ kotlinc -script list_folders.kts "path_to_folder_to_inspect"

Kotlin features in an overly complex "hello world" example

 1 fun main(args: Array<String>) {
 2     
 3     greet {
 4         to.place
 5     }.print()
 6 }
 7 
 8 // Inline higher-order functions
 9 inline fun greet(s: () -> String) : String = greeting andAnother s()
10 
11 // Infix functions, extensions, type inference, nullable types, 
12 // lambda expressions, labeled this, Elvis operator (?:)
13 infix fun String.andAnother(other : Any?) = buildString() 
14 { 
15     append(this@andAnother); append(" "); append(other ?: "") 
16 }
17 
18 // Immutable types, delegated properties, lazy initialization, string templates
19 val greeting by lazy { val doubleEl: String = "ll"; "he${doubleEl}o" }
20 
21 // Sealed classes, companion objects
22 sealed class to { companion object { val place = "world"} }
23 
24 // Extensions, Unit
25 fun String.print() = println(this)

Variables in Kotlin can be immutable, declared with the val keyword or mutable, declared with the var keyword.[15]

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(maybe: String?, neverNull: Int) {
   // use of elvis operator
   val name: String = maybe ?: "stranger"
   println("Hello $name")
}

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.[19]

// the following function takes a lambda, f, and executes f passing it the string, "lambda"
// note that (s: String) -> Unit indicates a lambda with a String parameter and Unit return type
fun executeLambda(f: (s: 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") }

ToolsEdit

  • IntelliJ IDEA has plug-in support for Kotlin.[20] IntelliJ IDEA 15 is the first version to bundle the Kotlin plugin in the IntelliJ Installer, and provide Kotlin support out of the box.[21]
  • JetBrains also provides a plugin for Eclipse.[22][23]
  • Integration with common Java build tools is supported including Apache Maven,[24] Apache Ant,[25] and Gradle.[26]
  • Android Studio (based on IntelliJ IDEA) has official support for Kotlin, starting from Android Studio 3.[27]
  • Emacs has a Kotlin Mode in its Melpa package repository.

ApplicationsEdit

One of the obvious applications of Kotlin is Android development. The platform was stuck on Java 7 for a while (with some contemporary language features made accessible through the use of Retrolambda[28] or the Jack toolchain[29]) 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 (Android Studio[30]) it is intended to improve code readability, give an easier way to extend Android SDK classes and speed up development.[31]

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++.[32]

AdoptionEdit

According to the Kotlin website, Prezi is using Kotlin in the backend.[33] DripStat has done a writeup of their experience with Kotlin.[34]

According to Jetbrains blog, Kotlin is used by Amazon Web Services, Pinterest, Coursera, Netflix, Uber, Square, Trello, Basecamp,[35] and others. 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, Société Générale), has over 90% Kotlin in its codebase.[36]

According to Google, Kotlin has already been adopted by several major developers — Expedia, Flipboard, Pinterest, Square, and others — for their Android production apps.[37]

According to Microsoft, Kotlin "is definitely a trend" for the development of Android apps at the company, including Sticky Notes and Microsoft To-Do. "Many teams have already moved to Kotlin and all new code that they develop is written in Kotlin."[38]

See alsoEdit

ReferencesEdit

  • This article contains quotations from Kotlin tutorials which are released under a Apache 2.0 license.
  1. ^ https://github.com/JetBrains/kotlin/releases/latest
  2. ^ "kotlin-stdlib". kotlinlang.org. JetBrains. Retrieved April 20, 2018.
  3. ^ a b Shafirov, Maxim (May 17, 2017). "Kotlin on Android. Now official". Today, at the Google I/O keynote, the Android team announced first-class support for Kotlin.
  4. ^ "Kotlin FAQ". Kotlin lets you choose between generating Java 6 and Java 8 compatible bytecode. More optimal byte code may be generated for higher versions of the platform.
  5. ^ "Kotlin is now Google's preferred language for Android app development". TechCrunch. Retrieved 2019-05-08.
  6. ^ a b Krill, Paul (Jul 22, 2011). "JetBrains readies JVM language Kotlin". infoworld.com. InfoWorld. Retrieved February 2, 2014.
  7. ^ Waters, John (February 22, 2012). "Kotlin Goes Open Source". ADTmag.com/. 1105 Enterprise Computing Group. Retrieved February 2, 2014.
  8. ^ Mobius (2015-01-08), Андрей Бреслав — Kotlin для Android: коротко и ясно, retrieved 2017-05-28
  9. ^ Kieron Murphy (1996-10-04). "So why did they decide to call it Java?". Archived from the original on 2019-03-15.
  10. ^ "Why JetBrains needs Kotlin". we expect Kotlin to drive the sales of IntelliJ IDEA
  11. ^ "Kotlin 1.0 Released: Pragmatic Language for JVM and Android | Kotlin Blog". Blog.jetbrains.com. 2016-02-15. Retrieved 2017-04-11.
  12. ^ "Kotlin 1.2 Released: Sharing Code between Platforms | Kotlin Blog". Blog.jetbrains.com. 2017-11-28.
  13. ^ "JVM Languages Report extended interview with Kotlin creator Andrey Breslav". Zeroturnaround.com. April 22, 2013. Retrieved February 2, 2014.
  14. ^ "Semicolons". jetbrains.com. Retrieved February 8, 2014.
  15. ^ a b "Basic Syntax". Kotlin. Jetbrains. Retrieved 19 January 2018.
  16. ^ "functions". jetbrains.com. Retrieved February 8, 2014.
  17. ^ https://play.kotlinlang.org/byExample/01_introduction/01_Hello%20world. Missing or empty |title= (help)
  18. ^ Anko Github
  19. ^ "Higher-Order Functions and Lambdas". Kotlin. Jetbrains. Retrieved 19 January 2018.
  20. ^ "Kotlin :: JetBrains Plugin Repository". Plugins.jetbrains.com. 2017-03-31. Retrieved 2017-04-11.
  21. ^ "What's New in IntelliJ IDEA 2017.1". Jetbrains.com. Retrieved 2017-04-11.
  22. ^ "Getting Started with Eclipse Neon - Kotlin Programming Language". Kotlinlang.org. 2016-11-10. Retrieved 2017-04-11.
  23. ^ "JetBrains/kotlin-eclipse: Kotlin Plugin for Eclipse". GitHub. Retrieved 2017-04-11.
  24. ^ "Using Maven - Kotlin Programming Language". kotlinlang.org. Retrieved 2017-05-09.
  25. ^ "Using Ant - Kotlin Programming Language". kotlinlang.org. Retrieved 2017-05-09.
  26. ^ "Using Gradle - Kotlin Programming Language". kotlinlang.org. Retrieved 2017-05-09.
  27. ^ https://developer.android.com/kotlin/index.html
  28. ^ "orfjackal/retrolambda: Backport of Java 8's lambda expressions to Java 7, 6 and 5". GitHub. Retrieved 2017-05-09.
  29. ^ "Jack (Java Android Compiler Kit) | Android Open Source Project". source.android.com. Retrieved 2016-04-15.
  30. ^ "JetBrains Plugin Repository :: Kotlin". plugins.jetbrains.com. Retrieved 2016-04-15.
  31. ^ "Will Kotlin Replace Java?". themindstudios.com. Retrieved 2017-03-10.
  32. ^ Lardinois, Frederic (2017-05-17). "Google makes Kotlin a first-class language for writing Android apps". techcrunch.com. Retrieved 2018-06-28.
  33. ^ "Kotlin Programming Language". Kotlinlang.org. Retrieved 2017-04-11.
  34. ^ "Kotlin in Production - What works, Whats broken". Blog.dripstat.com. 2016-09-24. Retrieved 2017-04-11.
  35. ^ "How we made Basecamp 3's Android app 100% Kotlin – Signal v. Noise". Signal v. Noise. 2017-04-29. Retrieved 2017-05-01.
  36. ^ "Kotlin 1.1 Released with JavaScript Support, Coroutines and more". Retrieved 2017-05-01.
  37. ^ "Android Announces Support for Kotlin". 2017-05-17. Retrieved 2017-05-19.
  38. ^ Valiente, Cesar (2019-06-12). "Hello, world!". Medium. Retrieved 2019-06-12.


External linksEdit