编辑“︁
Kotlin
”︁
跳转到导航
跳转到搜索
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
{{NoteTA |G1=IT }} {{Infobox programming language | name = Kotlin | logo = [[File:Kotlin logo (2021-present).svg|Kotlin 圖標|180px]] | file_ext = {{mono|.kt}} {{mono|.kts}} | paradigm = [[编程范型|多范型]]:[[面向对象编程|面向对象]]、[[函数式编程|函数式]]、[[指令式编程|指令式]]、[[宣告式编程|宣告式]]、[[泛型编程|泛型]]、[[反射式编程|反射式]]、[[并发计算|并发]] | family = | released = 2011 | designer = [[JetBrains]] | developer = JetBrains與開源貢獻者 | typing = [[静态类型|靜態類型]]、[[类型推论]] | implementations = | dialects = | influenced by = [[Java]]、[[Scala]]、[[Groovy]]、[[C♯|C#]]、{{le|Gosu}} | platform = 輸出[[Java Virtual Machine|Java虛擬機]]、[[Java字节码]]以及[[JavaScript]][[原始碼]] | operating system = 任何支援[[JVM]]或是[[JavaScript]]的直譯器 | license = [[Apache许可证|Apache 2]] | wikibooks = }} '''Kotlin'''是一種在[[Java虛擬機]]上執行的[[静态类型|靜態型別]][[编程语言|程式語言]],它也可以被編譯成為[[JavaScript]]原始碼。 == 历史 == 2011年7月,[[JetBrains]]在[[俄羅斯]][[聖彼得堡]]的開發團隊推出Kotlin项目,其名稱來自於聖彼得堡附近的[[科特林島]]。<ref name="oracle_interview">{{cite web | title=The Advent of Kotlin: A Conversation with JetBrains' Andrey Breslav | url=http://www.oracle.com/technetwork/articles/java/breslav-1932170.html | first=Janice | last=Heiss | website=oracle.com | date=April 2013 | accessdate=February 2, 2014 | publisher=Oracle Technology Network | archive-date=2017-05-08 | archive-url=https://web.archive.org/web/20170508184943/http://www.oracle.com/technetwork/articles/java/breslav-1932170.html | dead-url=no }}</ref>2012年1月,著名期刊《{{le|Dr. Dobb's Journal}}》中Kotlin被认定为該月的最佳語言。<ref name="dobbs">{{cite web | url=http://www.drdobbs.com/jvm/language-of-the-month-kotlin/232600836 | title=Language of the Month: Kotlin | website=drdobbs.com | date=January 20, 2012 | accessdate=February 2, 2014 | first=Andrey | last=Breslav | archive-url=https://web.archive.org/web/20151022062235/http://www.drdobbs.com/jvm/language-of-the-month-kotlin/232600836 | archive-date=2015-10-22 | dead-url=yes }}</ref>。这是一个面向[[JVM]]的新语言,它已被开发一年之久。<ref name="announce">{{cite web | url=http://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 | archive-date=2014-07-15 | archive-url=https://web.archive.org/web/20140715172505/http://www.infoworld.com/d/application-development/jetbrains-readies-jvm-based-language-167875 | dead-url=no }}</ref>JetBrains负责人Dmitry Jemerov说,大多数语言没有他们正在寻找的特性,但是[[Scala]]除外。但是,他指出Scala的编译时间過長这一明显缺陷。<ref name="announce" />Kotlin的既定目标之一是像Java一样快速编译。2012年2月,JetBrains以[[Apache许可证|Apache 2许可证]]开源此项目。<ref name="open source">{{cite web|url=http://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|archive-date=2016-03-29|archive-url=https://web.archive.org/web/20160329122131/https://adtmag.com/articles/2012/02/22/kotlin-goes-open-source.aspx|dead-url=yes}}</ref> JetBrains希望这个新语言能够推动[[IntelliJ IDEA]]的销售。<ref>{{cite web|url=http://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|accessdate=2017-05-18|archive-date=2014-04-21|archive-url=https://web.archive.org/web/20140421050853/http://blog.jetbrains.com/kotlin/2011/08/why-jetbrains-needs-kotlin/|dead-url=yes}}</ref> 雖然与[[Java]]語法並不相容,但在[[JVM]]環境中Kotlin被設計成可以和Java程式碼相互運作,並可以重複使用如[[Java集合框架]]等的現有{{Tsl|en|Java Class Library|Java引用的函数库}}。Hathibelagal写道,“如果你正在为Android开发寻找一种替代编程语言,那么应该试下Kotlin。它很容易在Android项目中替代Java或者同Java一起使用。” Kotlin v1.0于2016年2月15日发布。<ref>{{cite web |url=http://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 |archive-date=2016-10-22 |archive-url=https://web.archive.org/web/20161022042831/https://blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/ |dead-url=no }}</ref>这被认为是第一个官方稳定版本,并且JetBrains已准备从该版本开始的长期向后兼容性。 在[[Google I/O]] 2017中,[[Google]]宣布在[[Android]]上为Kotlin提供最佳支持。<ref>{{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|accessdate=2017-05-18|archive-date=2021-01-31|archive-url=https://web.archive.org/web/20210131070003/https://blog.jetbrains.com/kotlin/2017/05/kotlin-on-android-now-official/|dead-url=no}}</ref> == 语法 == Kotlin很明顯受到[[Java]]、[[C♯|C#]]、[[JavaScript]]、[[Scala]]、[[Groovy]]等语言的影响。例如Kotlin可以直接通过<code>println("Hello, ${name}")</code>或<code>println("Hello, $name")</code>来使用字串模板,和古老的shell script类似。又如Kotlin中的分号是可选的,这类似JavaScript,而且Groovy、Scala也有同样的能力。Kotlin常量定义关键字是<code>val</code>(不同於变量定义关键字<code>var</code>),表示固定值,这功能来自Scala,Swift也有类似功能。 需要注意,Kotlin没有关键字<code>new</code>。 === 變量 === 使用<code>val</code>(全稱為value,即(固定的)值)關鍵字定義唯讀变量,定義後其值無法修改<ref>{{cite web|title=Basic Syntax|url=https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables|website=Kotlin|publisher=Jetbrains|accessdate=19 January 2018|archive-date=2021-01-29|archive-url=https://web.archive.org/web/20210129183205/https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables|dead-url=no}}</ref> <syntaxhighlight lang="Kotlin"> val a: Int = 1 // 定義a為`Int`類型的唯讀變量,其值為1 val b = 2 // 自動檢測b為`Int`類型 </syntaxhighlight> 使用<code>var</code>(全稱為variable,即變量)關鍵字定義可變變量。 <syntaxhighlight lang="Kotlin"> var x = 5 // App 定義一個`Int`,值為5 x = 1 // 修改值為1 </syntaxhighlight> === 函数 === 使用<code>fun</code>关键字定义一个函数。 <syntaxhighlight lang="Kotlin"> fun sum(a: Int, b: Int): Int { return a + b } </syntaxhighlight> 上例定义了一个传入两个Int变量,并返回两数之和的求和函数。 ===程序的入口点=== 类似于 C、 C++、 C#、 Java 和 Go , Kotlin 程序的[[入口点]]是一个名为“main”的函数。 main 函数有一个包含命令行选项的参数(从 Kotlin 1.3 开始是可选的)。 Kotlin 支持像 [[Perl]] 和 [[Unix shell]] 那样的{{link-en|字符串模板|String interpolation}}。 [[类型推论|类型推断]]也是支持的。 <syntaxhighlight lang="kotlin" line="1"> // Hello, world! 範例 fun main() { val scope = "World" println("Hello, $scope!") } fun main(args: Array<String>) { for (arg in args) { println(arg) } } </syntaxhighlight> === 函数扩展 === Kotlin與C#、JavaScript类似,能够扩展類別的新功能,而无需继承该類別,或使用像装饰器(decorator)这样的任何类型的设计模式(design pattern)。扩展函数可以称为Kotlin的核心,在标准库里到处充斥着扩展函数。 扩展函数是静态分发的,也就是說,它们不是以接收者类型为准的虚擬函數。这意味着调用的扩展函数是由函数调用所在的表达式的类型来决定的,而不是由表达式运行时求值结果决定的。 在下述例子中,String類別被扩展出一個成员lastChar。 <syntaxhighlight lang="kotlin" line="1"> package MyStringExtensions fun String.lastChar(): Char = get(length - 1) >>> println("Kotlin".lastChar()) </syntaxhighlight> 利用函数扩展,Kotlin也支持[[运算符重载]]: <syntaxhighlight lang="kotlin" line="1"> // overloading '+' operator using an extension method 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) Point(x=40, y=60) </syntaxhighlight> === getter和setter === Kotlin像C#一样支持属性(property)。 ===解包引數=== 類似Python, 解包(unpack)指的是对实际参数的解包,只需在前面加一个星號* 即可,如test(*a): <syntaxhighlight lang="kotlin" line="1"> fun main(args: Array<String>) { val list = listOf("args: ", *args) println(list) } </syntaxhighlight> ===函数嵌套=== Kotlin支持函数嵌套(nested functions),允許函數内再定义函數,類似JavaScript、C#与Python语言。 <syntaxhighlight lang="kotlin" line="1"> class User( val id: Int, val name: String, val address: String) { fun saveUser(user: User) { fun validate(user: User, value: String, fieldName: String) { if (value.isBlank()) { 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 } } </syntaxhighlight> ===解构声明=== Kotlin支持解构声明,这与Python的迭代解包相似。 例如, collection object 包含解構式可分離其元素: <syntaxhighlight lang="kotlin" line="1"> for ((index, element) in collection.withIndex()) { println("$index: $element") } </syntaxhighlight> ===抽象類別=== 抽象類別(Abstract classes)定義抽象或純虚擬(Pure Virtual)占位函数,需要被继承。抽象類別預設是open的。 <syntaxhighlight lang="kotlin" line="1"> // 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() { } fun animateTwice() { } } </syntaxhighlight> ===類別屬性=== Kotlin 提供下列的關鍵字來限制顶层(top-level)聲明,用于控制類別与成员在继承时的可见性(作用域)。它们可用於類別及其成員: <syntaxhighlight lang="kotlin"> public internal protected private </syntaxhighlight> 用于類別的成员声明时,含义如下: * public:全局可见。此为默认的类型。 * internal:在当前模块中可见。 * protected:在当前類別的一级子類別中可见,如果子類別再被继承,则在下一级子類別中不可见。 * private:在当前類別中可见。 用于顶层声明时,含义如下: * public:全局可见。此为默认的类型。 * internal:在当前模块中可见。 * private:在当前文件中可见。 例如: <syntaxhighlight lang="kotlin" line="1"> // 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!") } </syntaxhighlight> === 主构造函数 vs. 二級构造函数 === 在Kotlin 中類別可以有一个主构造函数以及多个二级构造函数。如果主构造函数没有注解或可见性说明,则<code>constructor</code>关键字可以省略。如果构造函数中没有其它操作,大括号也可以省略。 <syntaxhighlight lang="kotlin" line="1"> // Example of class using primary constructor syntax // (Only one constructor required for this class) class User( val nickname: String, val isSubscribed: Boolean = true) { ... } </syntaxhighlight> Kotlin 的二級构造函数更类似於 C++, C#, 和 Java。 <syntaxhighlight lang="kotlin" line="1"> // 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) { // ... } } </syntaxhighlight> === Anko library=== Anko 是一組為Kotlin 打造的[[函数库]],其功能是用來開發[[Android]] UI 應用程式,<ref>{{Cite web |url=https://github.com/Kotlin/anko |title=Anko Github |accessdate=2018-06-02 |archive-date=2020-12-13 |archive-url=https://web.archive.org/web/20201213112926/https://github.com/Kotlin/anko/ |dead-url=no }}</ref>隨著同類功能的{{link-en|Jetpack Compose}}發展,Anko現已棄用。<ref>{{Cite web |url=https://github.com/Kotlin/anko/blob/master/GOODBYE.md |title=anko/GOODBYE.md |access-date=2020-03-11 |archive-date=2022-04-28 |archive-url=https://web.archive.org/web/20220428121710/https://github.com/Kotlin/anko/blob/master/GOODBYE.md }}</ref> <syntaxhighlight lang="kotlin" line="1"> fun Activity.showAreYouSureAlert(process: () -> Unit) { alert( title = "Are you sure?", message = "Are you really sure?") { positiveButton("Yes") { process() } negativeButton("No") { cancel() } } } </syntaxhighlight> ===Kotlin 交互模式=== Kotlin除了[[编译]]成[[Java字节码]]运行,也可以作为[[脚本语言]]解释运行,此特性使得Kotlin可以以交互模式运行。交互模式是脚本语言具有的特性,[[解释器]]可以立即运行用户输入的代码,并反馈运行结果。典型的语言有[[Python]]、[[JavaScript]](在[[V8 (JavaScript引擎)|V8引擎]]支持下)、[[Ruby]]。 <syntaxhighlight lang="bash"> $ kotlinc-jvm type :help for help; :quit for quit >>> 2+2 4 >>> println("Welcome to the Kotlin Shell") Welcome to the Kotlin Shell >>> </syntaxhighlight> ===Kotlin 也是腳本語言=== Kotlin 亦可視為腳本語言(scripting language)。其腳本存成 Kotlin source file (.kts),即成為可執行檔。 <syntaxhighlight lang="kotlin" line="1"> // list_folders.kts import java.io.File val folders = File(args[0]).listFiles { file -> file.isDirectory() } folders?.forEach { folder -> println(folder) } </syntaxhighlight> 為了執行Kotlin 脚本,我們在运行编譯器時再加上{{mono|-script}}選項。 <syntaxhighlight lang="bash" line="1"> $ kotlinc -script list_folders.kts "path_to_folder_to_inspect" </syntaxhighlight> ===Kotlin 的 hello world 例子=== <syntaxhighlight lang="kotlin" line="1"> fun main(args: Array<String>) { 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() { append(this@andAnother); append(" "); append(other ?: "") } //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) </syntaxhighlight> ===空变量及其运算=== Kotlin对可以为空(nullable)的变量和不可以为空(non-nullable)的变量作了区分。所有的可空对象(nullable objects)必須在定义時加上 "?" 後置於类型之後。開發人员遇到nullable objects時要先確認: null-check 須被執行過,才能赋值。可空性是Kotlin类型系统中帮助开发者避免以往Java的[[NullPointerException]]错误的特性。 Kotlin 提供空安全(null-safe)运算符給開發人員: * {{mono|?.}} ({{tsl|en|Safe navigation operator}}) 可用於安全存取(safely access) 可能是空对象的函數或屬性。如果 object 為空(null), 该方法將不被调用,而且表达式的值一定為空(null)。 * {{mono|?:}} ({{tsl|en|Null coalescing operator}}) 通常稱為{{tsl|en|Elvis operator|艾维斯运算符}}(Elvis operator): <syntaxhighlight lang=kotlin> fun sayHello(maybe: String?, neverNull: Int) { // use of elvis operator val name: String = maybe ?: "stranger" println("Hello $name") } </syntaxhighlight> 使用安全導引(safe navigation)运算符: <syntaxhighlight lang=kotlin> // 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() </syntaxhighlight> ===高阶函数与lambda=== Kotlin 亦支持高阶函数和lambdas功能。lambda是一种匿名函数,允许开发者直接将表达式定义为函数,这类似于Python。<ref>{{cite web|title=Higher-Order Functions and Lambdas|url=https://kotlinlang.org/docs/reference/lambdas.html|website=Kotlin|publisher=Jetbrains|accessdate=19 January 2018|archive-date=2021-01-22|archive-url=https://web.archive.org/web/20210122222128/https://kotlinlang.org/docs/reference/lambdas.html|dead-url=no}}</ref> <syntaxhighlight lang=kotlin> // 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") } </syntaxhighlight> Lambdas 可用大括弧{{mono| { } }}來定义。如果lambda 夾帶參數,他們可定义在大括弧内,並以{{mono|->}}运算符區隔。 <syntaxhighlight lang="kotlin"> // 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") } </syntaxhighlight> == 参考资料 == {{Reflist|2}} == 外部連結 == * {{Official website|http://www.kotlinlang.org}} * [http://try.kotlinlang.org 官方範例] {{Wayback|url=http://try.kotlinlang.org/ |date=20201203211351 }} * [https://www.kotlincn.net 官方網站 - 中文翻譯] {{Wayback|url=https://www.kotlincn.net/ |date=20201027094529 }} *[http://www.tw511.com/2/24/880.html Kotlin教學] {{Wayback|url=http://www.tw511.com/2/24/880.html |date=20200608182609 }} {{-}} {{程序设计语言|Kotlin|state=collapsed}} [[Category:程序设计语言]] [[Category:Java平台]] [[Category:JVM程式語言]] [[Category:面向对象的编程语言]] [[Category:静态类型编程语言]] [[Category:使用Apache许可证的软件]] [[Category:自由軟體計劃]] [[Category:2011年软件]] [[Category:2011年建立的程式語言]]
摘要:
请注意,所有对Local Chinese Wikipedia的贡献均可能会被其他贡献者编辑、修改或删除。如果您不希望您的文字作品被随意编辑,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源(详情请见
Project:著作权
)。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)
导航菜单
个人工具
未登录
讨论
贡献
创建账号
登录
命名空间
页面
讨论
大陆简体
不转换
简体
繁體
大陆简体
香港繁體
澳門繁體
大马简体
新加坡简体
臺灣正體
查看
阅读
编辑
查看历史
更多
搜索
导航
首页
最近更改
随机页面
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息