Kotlin is a statically typed JVM language that enables code that is expressive, short, and readable. Spring framework 5.0 has good support for Kotlin.
Consider a simple Kotlin program illustrating a data class, as shown here:
import java.util.*
data class Todo(var description: String, var name: String, var
targetDate : Date)
fun main(args: Array<String>) {
var todo = Todo("Learn Spring Boot", "Jack", Date())
println(todo)
//Todo(description=Learn Spring Boot, name=Jack,
//targetDate=Mon May 22 04:26:22 UTC 2017)
var todo2 = todo.copy(name = "Jill")
println(todo2)
//Todo(description=Learn Spring Boot, name=Jill,
//targetDate=Mon May 22 04:26:22 UTC 2017)
var todo3 = todo.copy()
println(todo3.equals(todo)) //true
}
In fewer than 10 lines of code, we created and tested a data bean with three properties and the following functions:
- equals()
- hashCode()
- toString()
- copy()
Kotlin is strongly typed. But there is no need to specify the type of each variable explicitly:
val arrayList = arrayListOf("Item1", "Item2", "Item3")
// Type is ArrayList
Named arguments allow you to specify the names of arguments when calling methods, resulting in more readable code:
var todo = Todo(description = "Learn Spring Boot",
name = "Jack", targetDate = Date())
Kotlin makes functional programming simpler by providing default variables (it) and methods such as take, drop, and so on:
var first3TodosOfJack = students.filter { it.name == "Jack"
}.take(3)
You can also specify default values for arguments in Kotlin:
import java.util.*
data class Todo(var description: String, var name: String, var
targetDate : Date = Date())
fun main(args: Array<String>) {
var todo = Todo(description = "Learn Spring Boot", name = "Jack")
}
With all its features making the code concise and expressive, we expect Kotlin to be a language to be learned for the .
We will discuss more about Kotlin in Chapter 13, Working with Kotlin in Spring.