Kotlin真的會取代JAVA嗎?
自從Kotlin 成為 Android 開發一級語言,Kotlin確實以其實用,高效贏得了海外很多公司和開發者的認可,比如Square的Jake大神一直在推Kotlin。Kotlin在國外至少有將近2年的應用生產環境的實踐(非JetBrains內部實踐應用)。在移動開發中,相比iOS程式設計師,Android程式設計師總是很幸運,因為我們有很多優秀好用的工具(Android Studio等),選用Kotlin,則是Google 為開發者提供高效的開發工具的一貫作風。
先來晒一晒Kotlin的幾大特點:
Kotlin是靜態型別程式語言,用於現代多平臺應用,100%可與Java™和Android™互操作 [java] view plain copy
Kotlin是非常簡介的程式語言
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"
}
[java] view plain copy
Kotlin 很安全
Get rid of those pesky NullPointerExceptions, you know, The Billion Dollar Mistake
var output: String
output = null // Compilation error
Kotlin protects you from mistakenly operating on nullable types
val name: String? = null // Nullable type
println(name.length()) // Compilation error
And if you check a type is right, the compiler will auto-cast it for you
fun calculateTotal(obj: Any) {
if (obj is Invoice)
obj.calculateTotal()
}
[java] view plain copy
方便使用 相容JVM上現有library
Use any existing library on the JVM, as there’s 100% compatibility, including SAM support.
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
Flowable
.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 to
import kotlin.browser.window
fun onLoad() {
window.document.body!!.innerHTML += "
Hello, Kotlin!"
}