Kotlin (programming language)

Kotlin (/ˈkɒtlɪn/)[2] 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,[3] 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). Language development costs are borne by JetBrains, while the Kotlin Foundation protects the Kotlin trademark.[4]

Kotlin
ParadigmMulti-paradigm: object-oriented, functional, imperative, block structured, declarative, generic, reflective, concurrent
Designed byJetBrains
DeveloperJetBrains
First appeared2011
Stable release
1.3.72 / 15 April 2020 (2020-04-15)[1]
Typing disciplineInferred, static, strong
Platform
OSCross-platform
LicenseApache License 2.0
Filename extensions.kt, .kts, .ktm
Websitekotlinlang.org
Influenced by

On 7 May 2019, Google announced that the Kotlin programming language is now its preferred language for Android app developers.[5] 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.[6]

History

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

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

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

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

Kotlin v1.2 was released on 28 November 2017.[14] Sharing code between JVM and JavaScript platforms feature was newly added to this release (as of version 1.3 multiplatform programming is experimental[15]). Full-stack demo has been made with the new Kotlin/JS Gradle Plugin.[16][17]

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

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.[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 have the data type come after the variable name (and with a colon separator), similar to Pascal and TypeScript.

Variables in Kotlin can be read-only, declared with the val keyword, or mutable, declared with the var keyword.[20]

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

Kotlin 1.3 adds (experimental) support for contracts[22] (inspired by Eiffel's design by contract[23] programming paradigm)

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("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[24]). 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 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:

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 operator

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 }

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:

1 for ((key, value) in map) {
2     println("$key: $value")
3 }

Nested functions

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         require(value.isNotEmpty()) { "Can't save user ${user.id}: empty $fieldName" }
 6     }
 7     
 8     validate(user, user.name, "Name") 
 9     validate(user, user.address, "Address")
10     // Save user to the database 
11     ...
12 }

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.

 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 default

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 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 (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 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.

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

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(book1)
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)

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 (.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) }

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

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

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:

1 fun sayHello(maybe: String?, neverNull: Int) {
2     // use of elvis operator
3     val name: String = maybe ?: "stranger"
4     println("Hello $name")
5 }

An example of the use of the safe navigation operator:

1 // returns null if...
2 // - foo() returns null,
3 // - or if foo() is non-null, but bar() returns null,
4 // - or if foo() and bar() are non-null, but baz() returns null.
5 // vice versa, return value is non-null if and only if foo(), bar() and baz() are non-null
6 foo()?.bar()?.baz()

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

1 // the following function takes a lambda, f, and executes f passing it the string, "lambda"
2 // note that (s: String) -> Unit indicates a lambda with a String parameter and Unit return type
3 fun executeLambda(f: (s: String) -> Unit) {
4     f("lambda")
5 }

Lambdas are declared using braces, { } . If a lambda takes parameters, they are declared within the braces and followed by the -> operator.

1 // the following statement defines a lambda that takes a single parameter and passes it to the println function
2 val l = { c : Any? -> println(c) }
3 // lambdas with no parameters may simply be defined using { }
4 val l2 = { print("no parameters") }

Tools

  • IntelliJ IDEA has plug-in support for Kotlin.[26] IntelliJ IDEA 15 was the first version to bundle the Kotlin plugin in the IntelliJ Installer, and provide Kotlin support out of the box.[27]
  • JetBrains also provides a plugin for Eclipse.[28][29]
  • Integration with common Java build tools is supported including Apache Maven,[30] Apache Ant,[31] and Gradle.[32]
  • Android Studio (based on IntelliJ IDEA) has official support for Kotlin, starting from Android Studio 3.[33]
  • Emacs has a Kotlin Mode in its Melpa package repository.
  • Vim has a plugin maintained on Github.[34]

Applications

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

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

Adoption

In 2018, Kotlin was the fastest growing language on GitHub with 2.6 times more developers compared to 2017.[40] It's the fourth most loved programming language according to the 2020 Stack Overflow Developer Survey.[41]

Kotlin was also awarded the O'Reilly Open Source Software Conference Breakout Award for 2019.[42]

A number of companies have publicly stated using Kotlin:

gollark: https://www.youtube.com/watch?v=SSiRkpgwVKY (with an ESP8266 though).
gollark: I think I read that the ESP32's I²S hardware could do something vaguely PWM-like up to 80MHz.
gollark: I don't know *that* much. It just seems like it might require a lot of routing table entries on every node to work.
gollark: Based on skimming the disaster radio routing protocol bit, it doesn't really have any defenses against malicious devices fiddling with routing, and may scale poorly (not sure exactly how the routing tables work).
gollark: Not the hardwarey/RF stuff, more like how you can efficiently do routing (even in the face of possibly malicious devices connected) and whatnot.

See also

References

  • This article contains quotations from Kotlin tutorials which are released under an Apache 2.0 license.
  1. "JetBrains/kotlin". GitHub.
  2. "What is the correct English pronunciation of Kotlin?". 16 October 2019. Retrieved 9 November 2019.
  3. "kotlin-stdlib". kotlinlang.org. JetBrains. Retrieved 20 April 2018.
  4. "Kotlin Foundation - Kotlin Programming Language". Kotlin.
  5. "Kotlin is now Google's preferred language for Android app development". TechCrunch. Retrieved 8 May 2019.
  6. "Kotlin FAQ". Kotlin lets you choose the version of JVM for execution. By default, the Kotlin/JVM compiler produces Java 6 compatible bytecode. If you want to make use of optimizations available in newer versions of Java, you can explicitly specify the target Java version from 8 to 13. Note that in this case the resulting bytecode might not run on lower versions.
  7. Krill, Paul (22 July 2011). "JetBrains readies JVM language Kotlin". infoworld.com. InfoWorld. Retrieved 2 February 2014.
  8. Waters, John (22 February 2012). "Kotlin Goes Open Source". ADTmag.com/. 1105 Enterprise Computing Group. Retrieved 2 February 2014.
  9. Mobius (8 January 2015), Андрей Бреслав — Kotlin для Android: коротко и ясно, retrieved 28 May 2017
  10. Kieron Murphy (4 October 1996). "So why did they decide to call it Java?". Archived from the original on 15 March 2019. Retrieved 14 October 2017.
  11. "Why JetBrains needs Kotlin". we expect Kotlin to drive the sales of IntelliJ IDEA
  12. "Kotlin 1.0 Released: Pragmatic Language for JVM and Android | Kotlin Blog". Blog.jetbrains.com. 15 February 2016. Retrieved 11 April 2017.
  13. Shafirov, Maxim (17 May 2017). "Kotlin on Android. Now official". Today, at the Google I/O keynote, the Android team announced first-class support for Kotlin.
  14. "Kotlin 1.2 Released: Sharing Code between Platforms | Kotlin Blog". blog.jetbrains.com. 28 November 2017.
  15. "Multiplatform Projects - Kotlin Programming Language". Kotlin. Retrieved 4 April 2020. Working on all platforms is an explicit goal for Kotlin, but we see it as a premise to a much more important goal: sharing code between platforms. With support for JVM, Android, JavaScript, iOS, Linux, Windows, Mac and even embedded systems like STM32, Kotlin can handle any and all components of a modern application.
  16. "Kotlin/kotlin-full-stack-application-demo". Kotlin. 3 April 2020. Retrieved 4 April 2020.
  17. "Kotlin full stack app demo: update all involving versions to work with 1.3.70 release". youtrack.jetbrains.com. Retrieved 4 April 2020.
  18. "JVM Languages Report extended interview with Kotlin creator Andrey Breslav". Zeroturnaround.com. 22 April 2013. Retrieved 2 February 2014.
  19. "Semicolons". jetbrains.com. Retrieved 8 February 2014.
  20. "Basic Syntax". Kotlin. Jetbrains. Retrieved 19 January 2018.
  21. "functions". jetbrains.com. Retrieved 8 February 2014.
  22. "What's New in Kotlin 1.3 - Kotlin Programming Language". Kotlin. Retrieved 4 April 2020.
  23. "Design by Contract (DbC) design considerations". Kotlin Discussions. 16 August 2012. Retrieved 4 April 2020. Implement the full semantics of Eiffel DbC and improve upon it.
  24. "Kotlin Examples: Learn Kotlin Programming By Example".
  25. "Higher-Order Functions and Lambdas". Kotlin. Jetbrains. Retrieved 19 January 2018.
  26. "Kotlin :: JetBrains Plugin Repository". Plugins.jetbrains.com. 31 March 2017. Retrieved 11 April 2017.
  27. "What's New in IntelliJ IDEA 2017.1". Jetbrains.com. Retrieved 11 April 2017.
  28. "Getting Started with Eclipse Neon – Kotlin Programming Language". Kotlinlang.org. 10 November 2016. Retrieved 11 April 2017.
  29. "JetBrains/kotlin-eclipse: Kotlin Plugin for Eclipse". GitHub. Retrieved 11 April 2017.
  30. "Using Maven – Kotlin Programming Language". kotlinlang.org. Retrieved 9 May 2017.
  31. "Using Ant – Kotlin Programming Language". kotlinlang.org. Retrieved 9 May 2017.
  32. "Using Gradle – Kotlin Programming Language". kotlinlang.org. Retrieved 9 May 2017.
  33. "Kotlin and Android". Android Developers.
  34. "udalov/kotlin-vim: Kotlin plugin for Vim. Featuring: syntax highlighting, basic indentation, Syntastic support". GitHub. Retrieved 30 August 2019.
  35. "orfjackal/retrolambda: Backport of Java 8's lambda expressions to Java 7, 6 and 5". GitHub. Retrieved 9 May 2017.
  36. "Jack (Java Android Compiler Kit) | Android Open Source Project". source.android.com. Retrieved 15 April 2016.
  37. "JetBrains Plugin Repository :: Kotlin". plugins.jetbrains.com. Retrieved 15 April 2016.
  38. "Will Kotlin Replace Java?". themindstudios.com. Retrieved 10 March 2017.
  39. Lardinois, Frederic (17 May 2017). "Google makes Kotlin a first-class language for writing Android apps". techcrunch.com. Retrieved 28 June 2018.
  40. "The state of the Octoverse". Archived from the original on 22 March 2019. Retrieved 24 July 2019.
  41. "Stack Overflow Developer Survey 2020". Retrieved 28 May 2020.
  42. "Kotlin wins Breakout Project of the Year award at OSCON '19". Retrieved 24 July 2019.
  43. "Kotlin in Production – What works, Whats broken". Blog.dripstat.com. 24 September 2016. Retrieved 11 April 2017.
  44. "How we made Basecamp 3's Android app 100% Kotlin – Signal v. Noise". Signal v. Noise. 29 April 2017. Retrieved 1 May 2017.
  45. "Droidcon NYC 2016 - Kotlin in Production". Retrieved 24 July 2019.
  46. "Becoming bilingual@coursera". Retrieved 24 July 2019.
  47. "Rob Spieldenner on twitter". Retrieved 24 July 2019.
  48. "2017 Who's using Kotlin?". Retrieved 24 July 2019.
  49. "square/sqldelight". Retrieved 24 July 2019.
  50. "Dan Lew on Twitter". Retrieved 24 July 2019.
  51. "Duolingo on Twitter". Retrieved 13 April 2020.
  52. "Kotlin 1.1 Released with JavaScript Support, Coroutines and more". Retrieved 1 May 2017.
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.