DEV Community

Steve Crow
Steve Crow

Posted on • Originally published at Medium on

2

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 default [JpaSpecificationExecutor.findOne] returns an Optional. This extension function wraps it to return a nullable instead.
*/
fun <T> JpaSpecificationExecutor<T>.findOneOrNull(specification: Specification<T>): T? =
findOne(specification)
.orElse(null)

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

// Finding a single user using a specification
val filteredUser = userRepository.findOne(specification).orElseThrow { UserNotFoundException() }
// Finding a single user using a specification with nullable
val filteredUser = userRepository.findOneOrNull(specification) ?: throw UserNotFoundException()

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more