0

I was wondering, whether it is better (in a way of having clean code according to a best practice) to pass function as reference using a new code block (lambda expression) or using a callable reference to an existing declaration, whenever it is possible.

So it is better to use

jobRepository.findAll(spec).map(Job::toDto) 

or

jobRepository.findAll(spec).map { it.toDto() }
Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
Lukas Forst
  • 802
  • 1
  • 8
  • 25
  • 1
    I would say whatever is more readable in that case to you... Sometimes you have longer class names, then the `it.*`-notation is more readable... otherwise I (personally of course) prefer function references... it all depends... a bit related: [Is the property reference (`::test`) equivalent to a function accessing the property (`{ it.test }`) when passed as argument e.g. `() -> String`?](https://stackoverflow.com/questions/51842043/is-the-property-reference-test-equivalent-to-a-function-accessing-the-proper) – Roland Sep 24 '19 at 08:30

1 Answers1

2

The chapter for instatiating a function type in the official Kotlin language reference doesn't use your version of:

jobRepository.findAll(spec).map { it.toDto() }

I would also argue that the first option is easier to read because you can see the type on which the method is called.

In the end, I agree with Roland's comment that it's probably the best idea to just use whichever version is more readable in your specific scenario.

matkv
  • 652
  • 1
  • 7
  • 18