Using Kotlin Extension Functions in the Micronaut Framework
Take a tour of the extension functions in the Micronaut framework and learn to write your own
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Kotlin.
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
Kotlin Extension Functions
Before we get started writing the application, let’s touch briefly on what extension functions are and why they’re useful.
What Are Extension Functions?
The Kotlin documentation explains that extension functions are "an ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator."
They’re useful for writing new functions for classes in a third-party library or quickly creating new methods for common use cases of a class you otherwise can’t edit directly.
For example, perhaps your application often needs to take a list and swap the index of two items in the list.
To define a swap method for any mutable list, you could write:
fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}Then use it like it was a regular method of MutableList
val languages = mutableListOf('java', 'groovy', 'kotlin')
languages.swap(0, 2) // Will swap 'java' and 'kotlin' so kotlin comes firstUsing Extension Functions in an Application
To show off the extension functions available for use in Micronaut applications (and how to write your own), we’ll build a simple application that
-
Consumes this fun dad joke API (I love a good dad joke) with an HTTP client
-
Schedules the joke to "be sent" to someone [we won’t actually be integrating a message sender for simplicity]
-
Writes our own extension function for the client (as if it was provided by a third-party)
-
Puts everything together in a controller
-
Starts the application with the
startApplicationextension function
Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-app example.micronaut.micronautguide \
--features=kotlin-extension-functions,reactor,http-client,graalvm \
--build=gradle \
--lang=kotlin \
--test=junit|
Note
|
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
If you use Micronaut Launch, select Micronaut Application as application type and add kotlin-extension-functions, reactor, http-client, and graalvm features.
|
Note
|
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
The Micronaut Kotlin Extension Functions
We’re using the Micronaut Kotlin extension function library which aids Kotlin developers in writing more idiomatic code in Micronaut.
You can see the dokka docs for the full list of functions here.
Big credit is due to Alejandro Gomez for allowing for the use of his initial collection of extension functions!
Let’s see these functions in action!
Application
Right away let’s modify the generated Application.kt to use the startApplication extension function
We’re naming it ApplicationKt simply because this guide’s build file is auto-generated, and we want to match the mainClass name it generates. Application alone would be a preferable name outside the context of this guide.
<3> startApplication<ApplicationKt> here does the work of .build().mainClass(ApplicationKt::class.java).start(). Convenient!
DadJokeClient
Next we’ll build out our functionality. We’ll start by modelling the response types for the plain GET request for the Dad Joke API (that just return a random joke), as well as the paged results that are returned from the /search endpoint.
package example.micronaut
import io.micronaut.serde.annotation.Serdeable
@Serdeable //
data class DadJoke(val id: String, val joke: String, val status: Int)Then, we can create a standard Micronaut HTTP client for the DadJoke API endpoint, letting the @Client annotation implement the interface we define.
package example.micronaut
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Header
import io.micronaut.http.annotation.QueryValue
import io.micronaut.http.client.annotation.Client
import reactor.core.publisher.Mono
@Client("https://icanhazdadjoke.com/")
@Header(name = "Accept", value = "application/json")
interface DadJokeClient {
@Get
fun tellMeAJoke(): Mono<DadJoke>
@Get("/search?term={searchTerm}")
fun searchDadJokes(@QueryValue searchTerm: String): Mono<DadJokePagedResults>
}Note that while we are creating this client for the purposes of this guide, often something like this comes from a third-party library. Perhaps you’re getting it from a public dependency you don’t have permission to edit, or from another team within your company that has different priorities from your own team.
It could also be that you simply have a specific use case for the client involving specific setup for your application that doesn’t belong in the client.
Let’s see how we can extend this client to suit our own use case.
DadJokeController
We’ll create a controller to utilize the client’s standard GET for a random joke.
package example.micronaut
import io.micronaut.http.MediaType.TEXT_PLAIN
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import jakarta.inject.Inject
import reactor.core.publisher.Mono
@Controller("/dadJokes")
class DadJokeController {
@Inject
lateinit var dadJokeClient: DadJokeClient
@Get(uri = "/joke", produces = [TEXT_PLAIN])
fun getAJoke(): Mono<String> {
return Mono.from(dadJokeClient.tellMeAJoke()).map(DadJoke::joke)
}
}Now, say we have a particular way we want to use a client frequently, for example attaching common headers or filling in some parameters by default.
Let’s explore how we can extend the client for our benefit. We’ll define a method for the client to specifically look for jokes about dogs.
In your controller file, at the bottom, add this extension function definition:
While this is a simplified (and somewhat silly) example, you can imagine how with a more sophisticated API, this could be a very powerful tool to encapsulate common functionality and explicitly relate it to the appropriate class, rather than defining another class just to encapsulate this common routine.
We can then use this extension function within our controller by defining a /dogJoke endpoint
Now we have our application!
Writing some tests
Lastly, let’s use a few more convenient functions included in micronaut-kotlin-extension-functions in our test
Now we can test everything out!
Testing the Application
To run the tests:
./gradlew testThen open build/reports/tests/test/index.html in a browser to see the results.
Running the Application
To run the application, use the ./gradlew run command, which starts the application on port 8080.
Generate a Micronaut Application Native Executable with GraalVM
We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.
Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.
|
Note
|
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.
|
GraalVM Installation
sdk install java 25.0.2-graalFor installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.
The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.
Alternatively, you can use the GraalVM Community Edition:
sdk install java 25.0.2-graalceNative Executable Generation
To generate a native executable using Gradle, run:
./gradlew nativeCompileThe native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.
It is possible to customize the name of the native executable or pass additional parameters to GraalVM:
Whether you run the application via Gradle or as a Native Executable, you should be able to get a good laugh by typing:
curl localhost:8080/dadJokes/jokeor
curl localhost:8080/dadJokes/dogJokesHopefully it brings a smile to your day!
Next Steps
See all the useful libraries for Micronaut Kotlin developers in the Micronaut Kotlin documentation.
Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
License
|
Note
|
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |