官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 常德市| 广德县| 濉溪县| 宜城市| 上栗县| 万全县| 垫江县| 洞头县| 永靖县| 怀远县| 临洮县| 襄垣县| 灌阳县| 静宁县| 闸北区| 汶川县| 宁河县| 界首市| 东源县| 若羌县| 彩票| 乳山市| 柳江县| 清新县| 双牌县| 潜江市| 关岭| 凤山市| 新蔡县| 宜昌市| 顺义区| 黄陵县| 孝昌县| 赤峰市| 左权县| 岳池县| 乐平市| 盘山县| 迭部县| 天台县| 平顺县|