Java Optional and Kotlin Nullable

We are using Kotlin and Spring Boot in one of our projects. This includes Spring Boot Jpa Repositories. We are using a CrudRepository that provides basic functionalities like save(), delete(), findById() etc. This library is written in Java, hence method signatures look like this:

Optional<T> findById(ID var1); 

Using this API out of the box would force us to deal with cumbersome Java Optionals. Since we are implementing in Kotlin we would like to use Kotlin Nullables instead and as it turned out we can achieve this very easily.

This is where extensions can help a lot. I already knew the concept of extensions from Swift and found that Kotlin also supports extensions. They enable us to add functionality to classes that we cannot change or subclass, for example java.util.Optional as it is final.

So all I need is a simple piece of code that converts a Java Optional into a Kotlin Nullable. Ideally this should be available on any Java Optional object (in our project only). We can achieve this by simply extending the Java Optional class as follows:

fun <T : Any> Optional<T>.toNullable(): T? = this.orElse(null)

I created the following test to verify that the extension works as intended:

 fun `can convert Java Optional to Kotlin Nullable`() {
   val optionalString = Optional.of("any String")
   val nullableString: String? = optionalString.toNullable()
   assertThat(nullableString).isEqualTo("any String")

   val emptyOptionalString: Optional<String> = Optional.empty()
   val emptyNullableString: String? = emptyOptionalString.toNullable()

Now we can wrap the call to the repository into a service that returns a Kotlin Nullable instead of a Java Optional as follows:

 class MyService constructor(@Autowired val myRepository: MyRepository) {
     fun getById(anId: Long): MyEntity? 
         = myRepository.findById(anId).toNullable()

Now we can use all the handy things that come with Kotlin Nullables, like Elvis, better readability and so on.