Using kotlin to improve java code



This article mainly gives several examples of how kotlin can improve java code.

String literal value and template

  • String literal value
    fun testStringLiterals(){
        val a = """if(a > 1) {
          |    return a

        val b = """Foo

With the literal value of strings, writing sql or something will not require so much effort to splice strings.

  • String template
    fun testStringTemplate() {
        val name = "hello kotlin"
        println("Hello, $name!");
        val data = listOf(1,2,3)
        println("Hello, ${data[0]}!")

This string template is even more powerful, equivalent to a built-in freemarker, and does not need to manually pass variable values

Gets the current index in the for loop.

    fun testForEachIndex(){
        val items = listOf("apple", "banana", "kiwifruit")
        for (index in items.indices) {
            println("item at $index is ${items[index]}")

In java, if you want to get index for each loop, you have to declare index outside. it’s too awkward to count for yourself.

data class

    data class Customer(val name: String, val email: String)

    fun testDataClass(){
        val customer = Customer("admin","")

Java always declares getter/setter. The advantage is that you can find those methods in the IDE that call getter/setter.

Lombok can automatically generate getter/setter and @Data annotation can also generate equal/hashcode methods, but lombok is not convenient to find those methods in the IDE. Getter/setter is called. Kotlin’s data class helps you solve these problems.

Null Safety

    fun testIfNotNull(){
        val files = File("Test").listFiles()
        println(files?.size)  //null

    fun testIfNotNullAndElse(){
        val files = File("Test").listFiles()
        println(files?.size ?: "empty")

This Null Safety is too useful. It is simpler than java’s ternary expression. When the expression is true, you don’t need to write the content to be returned repeatedly, just write the else part.

Null Safety is more useful in streaming/chain calls.

// 如果 `person` 或者 `person.department` 其中之一为空,都不会调用该函数:
person?.department?.head = managersPool.getManager()


This article only gives a few examples of kotlin’s ability to improve java code. kotlin is too powerful and its goal is to replace java. Many of these designs can see scala’s shadow, but there are many black magic, and the learning curve is a little shaky, but if you don’t use too high-level grammar, it’s OK.