0

I am using Kotlin in a spring boot application. Especially in the services, I have found that some of the function need to suppress the returned value from repository. For example, here is a save() that saves an entity without returning the persisted entity id:

fun save(person: Person) {
    personRepository.save(person)
}

As you can see that this function simply delegates the call to the JpaRepository#save(...) and does not return anything. What I wanted to do was something like this:

fun save(person: Person) = personRepository.save(person)

In order to do this, I have created an extension function:

fun Any.ignoreReturn() = Unit

and then make the call to the `personRepository#save(...) as:

fun save(person: Person) = personRepository.save(person).ignoreReturn()

What I wanted to know was:

  1. Is this the right way to do it?
  2. Are there side effects to such extension function as I am extending Any?
Prashant
  • 4,775
  • 3
  • 28
  • 47

1 Answers1

1

One way could be to do it like this:

fun save(person: Person): Unit = let { personRepository.save(person) }

Important part there is to declare the function to return Unit so the generated code from let wont need to return what personRepository.save(person) is returning. You can test it, just remove : Unit part and you get different signature for your save function.

vilpe89
  • 4,656
  • 1
  • 29
  • 36