Kotlin--Java程序员的救世主

2017 年 9 月 1 日 待字闺中 键客

编程语言层出不穷,只统计JVM上的语言就有不下几十种。现在的一些新的语言,都有很多的语法特点、语法糖,让代码越来越短、越来越酷,这也让Java程序员羡慕不已。不过,Java8有一个巨大的进步,就是Stream API以及lambda表达式的引入,编程的思维有一定的进步,代码量一定程度减少,但是还不够。

其实,JVM上的Groovy、Clojure、Scala,以及Xtend,都有各自的特点,我也都相继写过一些项目,但都没有在团队中推广。直到遇到Kotlin,花了半天时间看了下内容,果断开始在一个项目中采用,项目上线之后,就在团队中推广开来。确实是看了半天就开始开发,有Java基础的话,就是这么快。我们这里并不是用Kotlin做Android的项目,而是后端的服务。Kotlin,有几个快速上手的保证点:

  • JetBrains出品,完美的IDE支持。如果开始语法不熟悉,可以直接拷贝粘贴,自动转换Java到Kotlin。

  • 和Java无缝集成,比Clojure,Scala等方便太多。

  • 完美满足Java程序员对函数编程的向往

Java与Kotlin的比较资料

  1. https://fabiomsr.github.io/from-java-to-kotlin/index.html

  2. https://fabiomsr.github.io/from-java-to-kotlin/functions.html

  3. https://fabiomsr.github.io/from-java-to-kotlin/classes.html

  4. https://stackoverflow.com/documentation/kotlin/topics

下面具体介绍一些,我们实践中觉得很好用的点。

包级方法,再也不用定义类(累)了。

fun main(args: Array<String>) {
    println("Hello Kotlin!")

    sayHello("World")
}

fun sayHello(name: String) {
    println("Hello $name!")
}

集合框架的使用

  1. sortedBy/groupBy使用

  2. firstOrNull,注意如果集合为空,不能用first

  3. any,filter使用

  4. toMap

    • associateBy

    • map to

    • associate

  5. 使用.filterNotNull()
    例子:

data class User(val name: String, val age: Int)

val users = listOf(User("A", 1), User("B", 2), User("C", 3), User("D", 3))

fun main(args: Array<String>) {
    users.sortedBy { it.age }.reversed().forEach {
        println(it)
    }

    users.groupBy { it.age }.forEach {
        println(it)
    }

    println(users.any { it.age > 1 })

    users.filter { it.age > 4 }.first()
    println(users.filter { it.age > 4 }.firstOrNull())

    println(users.associateBy { it.name })

    println(users.map { it.name to it.age }.toMap())

    println(users.associate { it.name to it })

    users.map { it.name }
    println(users.filterNotNull())
}

方法扩展

这应该可以评为最强大的功能

fun Any.printIt() = println(this.toString())

fun main(args: Array<String>) {
    "abc".printIt()
    1L.printIt()
    User("ABC", 1).printIt()
}

属性get, set的使用

class Page {
    var page: Int = 1
        set(value) {
            if (value == null) {
                throw IllegalArgumentException()
            }
            if (value < 1) {
                throw IllegalArgumentException()
            }
            field = value
        }
    var size: Int = 20
        get() = field * 20

    override fun toString(): String {
        return "Page(page=$page, size=$size)"
    }

}

fun main(args: Array<String>) {
    val page = Page()
    page.page = -1
    page.size = 2
    page.printIt()
}

更方便的方法重载

@JvmOverloads
fun show(name: String, age: Int = 1, gender: String = "男") {
    println("name=$name, age=$age, gender=$gender")
}

fun main(args: Array<String>) {
    show("A")
    show("A", 2)
    show("A", 3, "男")
    show("A", gender = "男")
}

静态方法使用

class Helper {
    companion object {
        fun showSomething() {
            println("Something")
        }
    }
}

fun main(args: Array<String>) {
    Helper.showSomething()
}

一些小点

  • == 相当于equals

  • isNullOrBlank, string可以判断null

  • ?:操作
    示例:

fun main(args: Array<String>) {
    val str1 = "abc"
    val str2 = String("abc".toByteArray())

    println(str1 == str2)
    println(str1 === str2)

    var str3: String? = null
    println(str3.isNullOrBlank())

    println(str3 ?: "empty string")

    str3 = "1"
    str3?.let { print(it) }
}

if/else try/cache when,比switch强大太多

fun main(args: Array<String>) {
    val a = 1
    val b = 2
    val c = if (a > b) a else b
    println(c)

    val d = when(a) {
        1 -> 10
        2 -> 20
        else -> 0
    }
    println(d)
}

变长参数 array to vargs

fun printAll(vararg str: Any) {
    str.forEach {
        println(it)
    }
}

fun main(args: Array<String>) {
    printAll("1", "2", "3")
    printAll()

    val abc = listOf("a", "b", "c")
    printAll(*abc.toTypedArray())
}

?.let{}使用,减少null判断

if (account.mobile != null) {
    account.mobile = "*****"
}
// 一行搞定
account.mobile?.let { it = "******" }

多行字符串,写SQL爽不爽!

fun main(args: Array<String>) {
    val str = """
        a
        b
        c
    """

    str.printIt()
}

字符串插值,终于可以这样写了!

val a = "world"
println("hello $a")

try-with-resource的kotlin版本更容易

@InlineOnly
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var closed = false
    try {
        return block(this)
    } catch (e: Exception) {
        closed = true
        try {
            this?.close()
        } catch (closeException: Exception) {
        }
        throw e
    } finally {
        if (!closed) {
            this?.close()
        }
    }
}
登录查看更多
0

相关内容

Kotlin 是一种运行于 Java 虚拟机上的静态类型编程语言。
一份简明有趣的Python学习教程,42页pdf
专知会员服务
76+阅读 · 2020年6月22日
【实用书】Python技术手册,第三版767页pdf
专知会员服务
229+阅读 · 2020年5月21日
Python计算导论,560页pdf,Introduction to Computing Using Python
专知会员服务
70+阅读 · 2020年5月5日
【资源】100+本免费数据科学书
专知会员服务
105+阅读 · 2020年3月17日
【干货】大数据入门指南:Hadoop、Hive、Spark、 Storm等
专知会员服务
94+阅读 · 2019年12月4日
【电子书】Flutter实战305页PDF免费下载
专知会员服务
20+阅读 · 2019年11月7日
机器学习入门的经验与建议
专知会员服务
90+阅读 · 2019年10月10日
用 Python 开发 Excel 宏脚本的神器
私募工场
26+阅读 · 2019年9月8日
GitHub 热门:Python 算法大全,Star 超过 2 万
Python开发者
9+阅读 · 2019年4月27日
Python用法速查网站
Python程序员
17+阅读 · 2018年12月16日
实战 | 用Python做图像处理(三)
七月在线实验室
15+阅读 · 2018年5月29日
实战 | 用Python做图像处理(二)
七月在线实验室
17+阅读 · 2018年5月25日
Python 杠上 Java、C/C++,赢面有几成?
CSDN
6+阅读 · 2018年4月12日
Python机器学习教程资料/代码
机器学习研究会
8+阅读 · 2018年2月22日
开源巨献:阿里巴巴最热门29款开源项目
算法与数据结构
5+阅读 · 2017年7月14日
Arxiv
91+阅读 · 2020年2月28日
Arxiv
3+阅读 · 2018年10月18日
Efficient and Effective $L_0$ Feature Selection
Arxiv
5+阅读 · 2018年8月7日
Arxiv
3+阅读 · 2018年4月5日
VIP会员
相关VIP内容
一份简明有趣的Python学习教程,42页pdf
专知会员服务
76+阅读 · 2020年6月22日
【实用书】Python技术手册,第三版767页pdf
专知会员服务
229+阅读 · 2020年5月21日
Python计算导论,560页pdf,Introduction to Computing Using Python
专知会员服务
70+阅读 · 2020年5月5日
【资源】100+本免费数据科学书
专知会员服务
105+阅读 · 2020年3月17日
【干货】大数据入门指南:Hadoop、Hive、Spark、 Storm等
专知会员服务
94+阅读 · 2019年12月4日
【电子书】Flutter实战305页PDF免费下载
专知会员服务
20+阅读 · 2019年11月7日
机器学习入门的经验与建议
专知会员服务
90+阅读 · 2019年10月10日
相关资讯
用 Python 开发 Excel 宏脚本的神器
私募工场
26+阅读 · 2019年9月8日
GitHub 热门:Python 算法大全,Star 超过 2 万
Python开发者
9+阅读 · 2019年4月27日
Python用法速查网站
Python程序员
17+阅读 · 2018年12月16日
实战 | 用Python做图像处理(三)
七月在线实验室
15+阅读 · 2018年5月29日
实战 | 用Python做图像处理(二)
七月在线实验室
17+阅读 · 2018年5月25日
Python 杠上 Java、C/C++,赢面有几成?
CSDN
6+阅读 · 2018年4月12日
Python机器学习教程资料/代码
机器学习研究会
8+阅读 · 2018年2月22日
开源巨献:阿里巴巴最热门29款开源项目
算法与数据结构
5+阅读 · 2017年7月14日
Top
微信扫码咨询专知VIP会员