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

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.

主站蜘蛛池模板: 旅游| 巴东县| 万宁市| 康乐县| 通山县| 泰宁县| 诸城市| 黑河市| 边坝县| 海口市| 南丰县| 客服| 仁怀市| 铁岭县| 清新县| 商都县| 宜宾县| 陈巴尔虎旗| 通州区| 会昌县| 广河县| 宾阳县| 莱芜市| 得荣县| 庆城县| 宣武区| 城固县| 六盘水市| 石河子市| 汪清县| 体育| 尼玛县| 灌云县| 辽中县| 蒙自县| 长葛市| 乌审旗| 马尔康县| 井冈山市| 涿鹿县| 康马县|