// overloading '+' operator using an extension methodoperator 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)
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.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 }}
解构声明
Kotlin支持解构声明,这与Python的迭代解包相似。
例如, collection object 包含析构式可分离其元素:
for ((index, element) in collection.withIndex()) { println("$index: $element")}
// No need for the open keyword here, its already open by defaultabstract class Animated { // This virtual function is already open by default as well abstract fun animate() open fun stopAnimating() { } fun animateTwice() { }}
// Class is visible only to current moduleinternal 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!")}
// Example of class using primary constructor syntax// (Only one constructor required for this class)class User( val nickname: String, val isSubscribed: Boolean = true) { ...}
Kotlin 的二级构造函数更类似于 C++, C#, 和 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) { // ... }}
Anko library
Anko 是一组为Kotlin 打造的函数库,其功能是用来开发Android UI 应用程序,现已弃用。
fun Activity.showAreYouSureAlert(process: () -> Unit) { alert( title = "Are you sure?", message = "Are you really sure?") { positiveButton("Yes") { process() } negativeButton("No") { cancel() } }}
fun sayHello(maybe: String?, neverNull: Int) { // use of elvis operator val name: String = maybe ?: "stranger" println("Hello $name")}
使用安全导引(safe navigation)运算符:
// 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-nullfoo()?.bar()?.baz()
// 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 typefun executeLambda(f: (s: String) -> Unit) { f("lambda")}
// the following statement defines a lambda that takes a single parameter and passes it to the println functionval l = { c : Any? -> println(c) }// lambdas with no parameters may simply be defined using { }val l2 = { print("no parameters") }
^ Heiss, Janice. The Advent of Kotlin: A Conversation with JetBrains' Andrey Breslav. oracle.com. Oracle Technology Network. April 2013 . (原始内容存档于2017-05-08).
^ Breslav, Andrey. Language of the Month: Kotlin. drdobbs.com. January 20, 2012 . (原始内容存档于2015-10-22).
^ Waters, John. Kotlin Goes Open Source. ADTmag.com/. 1105 Enterprise Computing Group. February 22, 2012 . (原始内容存档于2016-03-29).
^ Why JetBrains needs Kotlin. . (原始内容存档于2014-04-21). we expect Kotlin to drive the sales of IntelliJ IDEA
^ Kotlin 1.0 Released: Pragmatic Language for JVM and Android | Kotlin Blog. Blog.jetbrains.com. 2016-02-15 . (原始内容存档于2016-10-22).
^ Shafirov, Maxim. Kotlin on Android. Now official. May 17, 2017 . (原始内容存档于2021-01-31). Today, at the Google I/O keynote, the Android team announced first-class support for Kotlin.