sequence
This article mainly gives several examples of how kotlin can improve java code
String literals and templates
String literal value
@Test fun testStringLiterals(){ val a = """if(a > 1) { | return a |}""".trimMargin() println(a) val b = """Foo Bar""".trimIndent() println(b) }With string literals, you don't have to do that much effort to splice strings if you write SQL.
String template
@Test 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 pass variable values manually
Get the current index in the for loop
@Test 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 the index outside and count it yourself. It's too awkward
data class
//Generate getter/setter, equals, hashcode, toString, copy, etc. //Setter only has data class Customer(val name: String, val email: String) @Test fun testDataClass(){ val customer = Customer("admin","[email protected]") println(customer) } Java always declares getter/setter. The advantage is that you can find those methods in the IDE that call getter/setter;
Although lombok can automatically generate getter/setter, and the @Data annotation can also generate equal/hashcode methods, lombok is not convenient to find those methods in the IDE, which call getter/setter; kotlin's data class helps you solve these problems
Null Safety
@Test fun testIfNotNull(){ val files = File("Test").listFiles() println(files?.size) //null } @Test fun testIfNotNullAndElse(){ val files = File("Test").listFiles() println(files?.size ?: "empty") }This Null Safety is so useful, it is a bit concise than java's ternary expression. When the expression is true, you don't need to repeat the content to be returned, just write the else part.
Null Safety is more useful when streaming/chained calls
// If one of `person` or `person.department` is empty, the function will not be called: person?.department?.head = managersPool.getManager()
summary
This article only gives a few examples of kotlin that can improve java code. kotlin is too powerful and the goal is to replace java. Many of the designs can see the shadow of scala, but there are also many black magic, and the learning curve is a little shaking, but it is OK if you don’t use too advanced grammar.
Related reference: https://www.kotlincn.net/docs/reference/