DEV Community

Steve Crow
Steve Crow

Posted on • Originally published at Medium on

Quick Tip: Kotlin, Spring Data, and Optionals

Quick Tip: Kotlin Extension Functions and Spring Data


Photo by Diego PH on Unsplash

When working with Spring Data and Kotlin, you may have noticed that the default findById returns an Optional . This super-short post will show you how you can leverage Kotlin extension functions to customize this logic.

What is Optional ?

Optional was introduced in Java 8 as a solution to handle nullability. It serves as a container that might contain a value, freeing you up from using null to mean optionally defined.

Kotlin addresses this using a different approach: being null-safe.

What are extension functions?

Extension functions allow you to extend a class with additional functionality without using decorators or having direct access to modifying the class.

They can be really useful when you want to add things to third-party libraries as if the function was part of the library.

Extending Spring Data

Spring Data added an extension function in 2.1.4 to CrudRepository called findByIdOrNull . However, this method doesn’t work in some of the other interfaces, like JpaSpecificationExecutor .

Here’s one I use for JpaSpecificationExecutor that wraps the findOne method:

By defining this extension function, I can now bypass the optional entirely and work directly with the nullable return value:

Conclusion

While Kotlin is fully interoperable with Java, we can do some things to improve the overall user experience. Stay tuned for more Quick Tips to help you on your Kotlin journey.

Oldest comments (0)