Kotlin language support

The Spring Framework 5.0 introduces a statically typed JVM language support the Kotlin language (https://kotlinlang.org/), which enables code that is short, readable, and expressive. Kotlin is basically an object-oriented language that runs on top of the JVM, and also supports functional programming style.

With Kotlin support, we can dive into functional Spring programming, especially for functional web endpoints and bean registration.

In Spring Framework 5.0, we can write clean and readable Kotlin code for web-functional APIs as follows:

{
("/bank" and accept(TEXT_HTML)).nest {
GET("/", bankHandler::findAllView)
GET("/{customer}", bankHandler::findOneView)
}
("/api/account" and accept(APPLICATION_JSON)).nest {
GET("/", accountApiHandler::findAll)
GET("/{id}", accountApiHandler::findOne)
}
}

With the Spring 5.0 version, Kotlin's null-safety support is also provided with the indicating annotations using @NonNull, @Nullable, @NonNullApi, and @NonNullFields from the org.springframework.lang package.

There are some newly added Kotlin extensions that basically add function extensions to the existing Spring APIs. For example, the extension fun <T : Any> BeanFactory.getBean(): T from the package org.springframework.beans.factory adds the support in org.springframework.beans.factory.BeanFactory for searching a bean by just specifying the bean type as Kotlin's reified type parameter without class argument:

@Autowired
lateinit var beanFactory : BeanFactory

@PostConstruct
fun init() {
val bankRepository = beanFactory.getBean<BankRepository>()

}

One more extension can be found in org.springframework.ui, which provides operator overloading support to add an array-like getter and setter to the model interface:

model["customerType"] = "Premium"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset