首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >你为什么应该学习 Kotlin ?

你为什么应该学习 Kotlin ?

作者头像
一个会写诗的程序员
发布2020-11-12 11:15:15
发布2020-11-12 11:15:15
5940
举报

Why Kotlin?

Concise

Drastically reduce the amount of boilerplate code

代码语言:javascript
复制
/*
 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

代码语言:javascript
复制
/*
 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()
}

Interoperable

Leverage existing libraries for the JVM, Android, and the browser

代码语言:javascript
复制
/*
 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 += "<br/>Hello, Kotlin!"
}

Tool-friendly

Choose any Java IDE or build from the command line

参考资料:

为什么要学习 Kotlin ? https://kotlinlang.org/


Kotlin开发者社区 :

https://www.jianshu.com/c/498ebcfd27ad

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • Why Kotlin?
    • Concise
    • Safe
    • Interoperable
    • Tool-friendly
    • 参考资料:
  • Kotlin开发者社区 :
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档