kotlinlambdafunction-reference

Best practice in instantiating a function type in Kotlin


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() }

Solution

  • 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.