- Kotlin Blueprints
- Ashish Belagali Hardik Trivedi Akshay Chordiya
- 283字
- 2021-07-02 21:50:11
Extension functions
The extension functions in Kotlin provide an easy way to add new functionality to an existing API in a non-intrusive way. Often, they are used to eliminate the need to write special utility or helper classes. They make the code more idiomatic and readable.
Here is an example of where an extension function is added to the library class (java.lang.String) to check if the string is an email or not:
fun String.isEmail(): Boolean {
// Logic to check if it's a email
}
This function will behave as a part of the String class, so you can achieve it as follows:
"kotlin.blueprints@packt.com".isEmail()
Where can the extension functions be used in the context of Spring Boot?
A case in point is where our Kotlin code needs to call the Java code and one needs to use JVM generics. But this could look ugly.
For example, here is how one would use the new WebClient from the Spring WebFlux API to retrieve a list of objects in Java:
Flux<Message> messages =
client.get().retrieve().bodyToFlux(Message.class)
Now, for Kotlin, the code becomes (note that the type is inferred):
val messages =
client.get().retrieve().bodyToFlux(Message::class.java)
Note that Message::class is a KClass and it needs to be converted to a Java class by adding .java to it. Doesn't it look ugly?
Now we could use an extension function and use Kotlin's reified type parameter to make the code cleaner and a workaround for JVM generics type, helping us to write or provide better APIs, as follows:
val messages = client.get().retrieve().bodyToFlux<Message>()
We now have a short and concise syntax.
The Spring Boot Framework 5.0 ships with a few useful extension functions. Of course, you can further write your own.
- Building a Home Security System with Raspberry Pi
- HTML5 移動Web開發從入門到精通(微課精編版)
- Python計算機視覺編程
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- Learning Network Forensics
- JAVA程序設計實驗教程
- Spring快速入門
- Java EE 8 Application Development
- Android系統原理及開發要點詳解
- 響應式架構:消息模式Actor實現與Scala、Akka應用集成
- Kotlin開發教程(全2冊)
- R數據科學實戰:工具詳解與案例分析
- 跟戴銘學iOS編程:理順核心知識點
- Deep Learning for Natural Language Processing
- HTML5與CSS3權威指南