Artur A
Artur A

Reputation: 297

How it is possible using Kotlin function features make this piece of code nicer?

I have these piece of codes and I don't like that I have mapNotNull and inside I have else cases which returns null, I think my kotlin knowledge is not enough to make it better, any thoughts?

    return config.mainMenus.mapNotNull { mainMenu ->
      val subPage = config.subPages.find {
        if (mainMenu.actions.isNotEmpty()) {
          it.id == mainMenu.actions.first().contentId
        } else {
          false
        }
      }
      if (subPage?.items?.isNotEmpty() != null) {
        MenuItem(mainMenu.type, mainMenu.titles, mainMenu.actions[0].type, subPage.items)
      } else {
        null
      }
    }
  }


  val programs = cards.mapNotNull { card ->
              if (card is Program) {
                epgRepository.getProgramProgress(currentTime = currentTime, program = card)
              } else {
                null
              }
            }

Upvotes: 1

Views: 97

Answers (1)

JArgente
JArgente

Reputation: 2297

You can replace the previous code with

            return config.mainMenus.mapNotNull { mainMenu ->
        config.subPages
                .find{mainMenu.actions.firstOrNull()?.contentId?.equals(it.id)?:false}
                ?.let{menu->
                    MenuItem(mainMenu.type, mainMenu.titles, mainMenu.actions[0].type, menu.items).takeIf{menu.items?.isNotEmpty()==true}
                }?:null
    }
}

Te second one could be

  val programs = cards.
      filterIsInstance<Program>().
      map { epgRepository.getProgramProgress(currentTime = currentTime, program = card)}

In this case you firstly filter the collection getting only the elements that are programs and only those are converted to the type that the function getProgramProcess return

Upvotes: 1

Related Questions