词条 | Kotlin (programming language) |
释义 |
| name = Kotlin | logo = Kotlin-logo.svg | paradigm = | released = 2011 | designer = JetBrains | developer = JetBrains and open-source contributors | latest release version = 1.3.21 | latest release date = {{Start date and age|2019|2|6}}[1] | typing = Inferred, static, strong | implementations = | dialects = | influenced by = {{Hlist|C#|Gosu|Groovy|Java|ML|Python|Scala}} | platform = JVM, JavaScript, LLVM | operating system = Cross-platform | license = Apache License 2.0 | file_ext = {{Unbulleted list|.kt|.kts}} | website = {{URL|kotlinlang.org}} | wikibooks = | caption = }} 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 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] HistoryIn July 2011, JetBrains unveiled Project Kotlin, a new language for the JVM, which had been under development for a year.[5] 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.[5] 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.[6] 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[7] (though the programming language Java was perhaps named after the coffee[8]). JetBrains hopes that the new language will drive IntelliJ IDEA sales.[9] Kotlin v1.0 was released on February 15, 2016.[10] 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.[11] 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. DesignDevelopment 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.[12] Semicolons are optional as a statement terminator; in most cases a newline is sufficient for the compiler to deduce that the statement has ended.[13]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 {{mono|val}} keyword, or mutable, declared with the {{mono|var}} keyword.[14] 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 {{mono|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.[15] 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. SyntaxFunctional programming styleKotlin 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 Main entry pointAs in C and C++, the entry point to a Kotlin program is a function named "main", which is 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(args: Array val scope = "World" println("Hello, $scope!") } Extension methodsSimilar 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(length - 1) >>> println("Kotlin".lastChar()) By placing the preceding code in the top-level of a package, the String class is extended to include a {{code|lastChar}} method that was not included in the original definition of the String class. // Overloading '+' operator using an extension method operator fun Point.plus(other: Point): Point { } >>> val p1 = Point(10, 20) >>> val p2 = Point(30, 40) >>> println(p1 + p2) Point(x=40, y=60) Unpack arguments with spread operatorSimilar to Python, the spread operator asterisk (*) unpacks an array's contents as comma-separated arguments to a function: fun main(args: Array val list = listOf("args: ", *args) println(list) } Deconstructor methods{{Distinguish|Destructor (computer programming)|text=the destructor method common in object oriented languages}}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 ((index, element) in collection.withIndex()) { } Nested functionsKotlin allows local functions to be declared inside of 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) { if (value.isEmpty()) { throw IllegalArgumentException("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 defaultIn 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. // 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 defaultAbstract classes 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, its already open by default abstract class Animated { // This virtual function is already open by default as well abstract fun animate() open fun stopAnimating() { } } Classes are public by defaultKotlin provides the following keywords to restrict visibility for top-level declaration, such as classes, and for class members: 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: // Class is visible only to current module internal open class TalkativeButton : Focusable { // 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!") } Primary constructor vs. secondary constructorsKotlin 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 // (Only one constructor required for this class) open class PowerUser : User ( protected val nickname: String, final override var isSubscribed: Boolean = true) { ... } 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 // (more than one constructor required for this class) class MyButton : View { // Constructor #1 constructor(ctx: Context) : super(ctx) { // ... } // Constructor #2 constructor(ctx: Context, attr: AttributeSet) : super(ctx, attr) { // ... } } Data ClassKotlin provides [https://www.tutorialkart.com/kotlin/data-class-in-kotlin/ Data Classes] to define classes that store only properties. In Java Programming, classes that store only properties are usual, 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(args: Array) { // create a data class object like any other class object var book1 = Book("Kotlin Programming",250) println(book) // output: Book(name=Kotlin Programming, price=250) } // data class with parameters and their optional default values data class Book(val name: String = "", val price: Int = 0) Anko libraryAnko is a library specifically created for Kotlin to help build Android UI applications.[16] fun Activity.showAreYouSureAlert(process: () -> Unit) { alert( title = "Are you sure?", message = "Are you really sure?") { positiveButton("Yes") { process() } negativeButton("No") { cancel() } } } Kotlin interactive shell$ kotlinc-jvm type :help for help; :quit for quit >>> 2+2 4 >>> println("Hello, World!") Hello, World! >>> Kotlin as a scripting languageKotlin can also be used as a scripting language. A script is a Kotlin source file (.kts) with top level executable code. // list_folders.kts import java.io.File val folders = File(args[0]).listFiles { file -> file.isDirectory() } folders?.forEach { folder -> println(folder) } To run a script, you pass the $ kotlinc -script list_folders.kts "path_to_folder_to_inspect" fun main(args: Array greet { to.place }.print() } // Inline higher-order functions inline fun greet(s: () -> String) : String = greeting andAnother s() // Infix functions, extensions, type inference, nullable types, // lambda expressions, labeled this, Elvis operator (?:) infix fun String.andAnother(other : Any?) = buildString() {} // Immutable types, delegated properties, lazy initialization, string templates val greeting by lazy { val doubleEl: String = "ll"; "he${doubleEl}o" } // Sealed classes, companion objects sealed class to { companion object { val place = "world"} } // Extensions, Unit fun String.print() = println(this) Variables in Kotlin can be immutable, declared with the {{mono|val}} keyword or mutable, declared with the {{mono|var}} keyword.[14] 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.[17] // 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) { } Lambdas are declared using braces, {{mono|{ } }}. If a lambda takes parameters, they are declared within the braces and followed by the {{mono|->}} 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") } Tools
ApplicationsOne 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[26] or the Jack toolchain[27]) 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[28]) it is intended to improve code readability, give an easier way to extend Android SDK classes and speed up development.[29] 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++.[30] AdoptionAccording to the Kotlin website, Prezi is using Kotlin in the backend.[31] DripStat has done a writeup of their experience with Kotlin.[32] According to Jetbrains blog, Kotlin is used by Amazon Web Services, Pinterest, Coursera, Netflix, Uber, Square, Trello, Basecamp,[33] 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. [34]According to Google, Kotlin has already been adopted by several major developers — Expedia, Flipboard, Pinterest, Square, and others — for their Android production apps.[35] See also{{Portal|Free and open-source software|Java (programming language)}}
References
1. ^https://github.com/JetBrains/kotlin/releases/latest 2. ^{{cite web|title=kotlin-stdlib|url=https://kotlinlang.org/api/latest/jvm/stdlib/index.html|website=kotlinlang.org|accessdate=April 20, 2018|publisher=JetBrains}} 3. ^1 {{cite web |url = https://blog.jetbrains.com/kotlin/2017/05/kotlin-on-android-now-official/ |title = Kotlin on Android. Now official |first = Maxim |last = Shafirov |quote = Today, at the Google I/O keynote, the Android team announced first-class support for Kotlin. |date = May 17, 2017 }} 4. ^{{cite web |url = https://kotlinlang.org/docs/reference/faq.html|title = Kotlin FAQ |quote = 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. ^1 {{cite web |url = https://www.infoworld.com/d/application-development/jetbrains-readies-jvm-based-language-167875 |publisher = InfoWorld |website = infoworld.com |first = Paul |last = Krill |title = JetBrains readies JVM language Kotlin |date = Jul 22, 2011 |accessdate = February 2, 2014 }} 6. ^{{cite web |url = https://adtmag.com/articles/2012/02/22/kotlin-goes-open-source.aspx |title = Kotlin Goes Open Source |first = John |last = Waters |date = February 22, 2012 |accessdate = February 2, 2014 |website = ADTmag.com/ |publisher = 1105 Enterprise Computing Group }} 7. ^{{Citation|last=Mobius|title=Андрей Бреслав — Kotlin для Android: коротко и ясно|date=2015-01-08|url=https://www.youtube.com/watch?v=VU_L2_XGQ9s|accessdate=2017-05-28}} 8. ^{{cite web|author=Kieron Murphy|title=So why did they decide to call it Java?|url=https://www.javaworld.com/article/2077265/core-java/so-why-did-they-decide-to-call-it-java-.html|date=1996-10-04|archive-url=http://web.archive.org/web/20190315171946/www.javaworld.com/article/2077265/so-why-did-they-decide-to-call-it-java-.html|archive-date=2019-03-15|dead-url=no}} 9. ^{{cite web |url = https://blog.jetbrains.com/kotlin/2011/08/why-jetbrains-needs-kotlin/ |title = Why JetBrains needs Kotlin |quote = we expect Kotlin to drive the sales of IntelliJ IDEA }} 10. ^{{cite web |url = https://blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/ |title = Kotlin 1.0 Released: Pragmatic Language for JVM and Android | Kotlin Blog |website = Blog.jetbrains.com |date = 2016-02-15 |accessdate = 2017-04-11 }} 11. ^{{cite web |url = https://blog.jetbrains.com/kotlin/2017/11/kotlin-1-2-released/ |title = Kotlin 1.2 Released: Sharing Code between Platforms | Kotlin Blog |website = Blog.jetbrains.com |date = 2017-11-28 }} 12. ^{{cite web |title = JVM Languages Report extended interview with Kotlin creator Andrey Breslav |url = https://zeroturnaround.com/rebellabs/jvm-languages-report-extended-interview-with-kotlin-creator-andrey-breslav/ |website = Zeroturnaround.com |date = April 22, 2013 |accessdate = February 2, 2014 }} 13. ^{{cite web |url = https://confluence.jetbrains.com/display/Kotlin/Grammar#Grammar-Semicolons |title = Semicolons |website = jetbrains.com |accessdate = February 8, 2014 }} 14. ^1 {{cite web|title=Basic Syntax|url=https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables|website=Kotlin|publisher=Jetbrains|accessdate=19 January 2018}} 15. ^{{cite web |url = https://confluence.jetbrains.com/display/Kotlin/Functions |title = functions |website = jetbrains.com |accessdate = February 8, 2014 }} 16. ^[https://github.com/Kotlin/anko Anko Github] 17. ^{{cite web|title=Higher-Order Functions and Lambdas|url=https://kotlinlang.org/docs/reference/lambdas.html|website=Kotlin|publisher=Jetbrains|accessdate=19 January 2018}} 18. ^{{cite web |url = https://plugins.jetbrains.com/plugin/6954-kotlin |title = Kotlin :: JetBrains Plugin Repository |website = Plugins.jetbrains.com |date = 2017-03-31 |accessdate = 2017-04-11 }} 19. ^{{cite web |url = https://www.jetbrains.com/idea/whatsnew/ |title = What's New in IntelliJ IDEA 2017.1 |website = Jetbrains.com |accessdate = 2017-04-11 }} 20. ^{{cite web |url = https://kotlinlang.org/docs/tutorials/getting-started-eclipse.html |title = Getting Started with Eclipse Neon - Kotlin Programming Language |website = Kotlinlang.org |date = 2016-11-10 |accessdate = 2017-04-11 }} 21. ^{{cite web |url = https://github.com/JetBrains/kotlin-eclipse |title = JetBrains/kotlin-eclipse: Kotlin Plugin for Eclipse |publisher = GitHub |accessdate = 2017-04-11 }} 22. ^{{cite web |url = https://kotlinlang.org/docs/reference/using-maven.html |title = Using Maven - Kotlin Programming Language |website = kotlinlang.org |accessdate = 2017-05-09 }} 23. ^{{cite web |url = https://kotlinlang.org/docs/reference/using-ant.html |title = Using Ant - Kotlin Programming Language |website = kotlinlang.org |accessdate = 2017-05-09 }} 24. ^{{cite web |url = https://kotlinlang.org/docs/reference/using-gradle.html |title = Using Gradle - Kotlin Programming Language |website = kotlinlang.org |accessdate = 2017-05-09 }} 25. ^https://developer.android.com/kotlin/index.html 26. ^{{cite web |url = https://github.com/orfjackal/retrolambda |title = orfjackal/retrolambda: Backport of Java 8's lambda expressions to Java 7, 6 and 5 |publisher = GitHub |access-date = 2017-05-09 }} 27. ^{{cite web|url=https://source.android.com/source/jack.html|title=Jack (Java Android Compiler Kit) {{!}} Android Open Source Project|website=source.android.com|access-date=2016-04-15}} 28. ^{{cite web |url = https://plugins.jetbrains.com/plugin/6954 |title = JetBrains Plugin Repository :: Kotlin |website = plugins.jetbrains.com |access-date = 2016-04-15 }} 29. ^{{cite web |url = https://themindstudios.com/blog/kotlin-vs-java-will-kotlin-replace-java/ |title = Will Kotlin Replace Java? |website = themindstudios.com |accessdate = 2017-03-10 }} 30. ^{{Cite news|url=https://techcrunch.com/2017/05/17/google-makes-kotlin-a-first-class-language-for-writing-android-apps/|title=Google makes Kotlin a first-class language for writing Android apps|last=Lardinois|first=Frederic|website=techcrunch.com|language=en-US|date=2017-05-17|access-date=2018-06-28}} 31. ^{{cite web |url = https://kotlinlang.org/ |title = Kotlin Programming Language |website = Kotlinlang.org |accessdate = 2017-04-11 }} 32. ^{{cite web |url = https://blog.dripstat.com/kotlin-in-production-the-good-the-bad-and-the-ugly-2/ |title = Kotlin in Production - What works, Whats broken |website = Blog.dripstat.com |date = 2016-09-24 |accessdate = 2017-04-11 }} 33. ^{{Cite news |url = https://m.signalvnoise.com/how-we-made-basecamp-3s-android-app-100-kotlin-35e4e1c0ef12 |title = How we made Basecamp 3’s Android app 100% Kotlin – Signal v. Noise |date = 2017-04-29 |work = Signal v. Noise |access-date = 2017-05-01 }} 34. ^{{Cite news |url = https://blog.jetbrains.com/kotlin/2017/03/kotlin-1-1/ |title = Kotlin 1.1 Released with JavaScript Support, Coroutines and more |access-date = 2017-05-01 }} 35. ^{{Cite news |url = https://android-developers.googleblog.com/2017/05/android-announces-support-for-kotlin.html |title = Android Announces Support for Kotlin |date = 2017-05-17 |access-date = 2017-05-19 }} External links
10 : Java programming language family|JVM programming languages|Object-oriented programming languages|Programming languages|Programming languages created in 2011|Software using the Apache license|Statically typed programming languages|High-level programming languages|2011 software|Free software projects |
随便看 |
|
开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。