Why Kotlin?
ConciseDrastically reduce the amount of boilerplate code/* Create a POJO with getters, setter...

-
Concise
Drastically reduce the amount of boilerplate code
/*Create a POJO with getters, setters, `equals()`, `hashCode()`, `toString()` and `copy()` in a single line:*/data class Customer(val name: String, val email: String, val company: String)// Or filter a list using a lambda expression:val positiveNumbers = list.filter { it > 0 }// Want a singleton? Create an object:object ThisIsASingleton {val companyName: String = "JetBrains"} -
Safe
Avoid entire classes of errors such as null pointer exceptions
/*Get rid of those pesky NullPointerExceptions, you know, The Billion Dollar Mistake*/var output: Stringoutput = null // Compilation error// Kotlin protects you from mistakenly operating on nullable typesval name: String? = null // Nullable typeprintln(name.length()) // Compilation error// And if you check a type is right, the compiler will auto-cast it for youfun calculateTotal(obj: Any) {if (obj is Invoice)obj.calculateTotal()} -
Interoperable
Leverage existing libraries for the JVM, Android, and the browser
/*Use any existing library on the JVM, as there’s 100% compatibility, including SAM support.*/import io.reactivex.Flowableimport io.reactivex.schedulers.SchedulersFlowable.fromCallable {Thread.sleep(1000) // imitate expensive computation"Done"}.subscribeOn(Schedulers.io()).observeOn(Schedulers.single()).subscribe(::println, Throwable::printStackTrace)// Target either the JVM or JavaScript. Write code in Kotlin and decide where you want to deploy toimport kotlin.browser.windowfun onLoad() {window.document.body!!.innerHTML += "<br/>Hello, Kotlin!"} -
Tool-friendly
Choose any Java IDE or build from the command line
Higher-Order Functions
A higher-order function is a function that takes another function as parameter and/or returns a function.
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int { // 1
return operation(x, y) // 2
}
fun sum(x: Int, y: Int) = x + y // 3
fun main() {
val sumResult = calculate(4, 5, ::sum) // 4
val mulResult = calculate(4, 5) { a, b -> a * b } // 5
println("sumResult $sumResult, mulResult $mulResult")
}
Output:
sumResult 9, mulResult 20
-
Declares a higher-order function. It takes two integer parameters,
xandy. Additionally, it takes another functionoperationas a parameter. Theoperationparameters and return type are also defined in the declaration. -
The higher order function returns the result of
operationinvocation with the supplied arguments. -
Declares a function that matches the
operationsignature. -
Invokes the higher-order function passing in two integer values and the function argument
::sum.::is the notation that references a function by name in Kotlin. -
Invokes the higher-order function passing in a lambda as a function argument. Looks clearer, doesn't it?
更多推荐



所有评论(0)