Hello everyone,
I’m beginner in Kotlin development and I have 2 ways for solving a problem.
As you can see in the snippets below, the first one uses “nested function” and the second uses a “local extension function as lambda”.
According to the functions and your experience, I’d like to ask:
- Which are the pros and cons related to each of the approaches (regarding performance, maintainability, readability, quality and good practices)?
- Do you suggest any other approach better than the below ones?
- Which one would you use?
Thanks in advance for your answers.
Option 1:
fun aggregateOption1(
param1: Param,
param2: Param,
): Int {
fun getSomethingFromParam(param: Param): Int {
return param.getCount()?.data
?: (param.data?.times(KG_TO_GRAMS)?.toInt())
?: 0
}
return getSomethingFromParam(param1) + getSomethingFromParam(param2)
}
.
.
Option 2:
fun aggregateOption2(
param1: Param,
param2: Param,
): Int {
val getSomething: Param.() -> Int = {
getCount()?.data
?: (data?.times(KG_TO_GRAMS)?.toInt())
?: 0
}
return param1.getSomething() + param2.getSomething()
}