https://kotlinlang.org logo
Title
p

popescustefanradu

01/20/2019, 1:05 PM
hey, I have a repository that returns a nullable object, how do i make a nice code that returns a field of that object if the object exists and otherwise does some other business?
t

thana

01/20/2019, 1:36 PM
you could make use of an extension funktion with nullable receiver
p

popescustefanradu

01/20/2019, 2:49 PM
like what?
i ended up with something like this:
fun getConfigByAgentName(agentName: String): String {
        var agentConfig = configRepository.findByName(agentName)?.configText
        if (agentConfig != null) {
            return agentConfig
        }
        agentConfig = computeConfig(agentName)
        configRepository.save(Config(name = agentName, addedAt = LocalDateTime.now(), configText = agentConfig))
        return agentConfig
    }
a

aarjav

01/20/2019, 5:21 PM
Is repository some Android thing?
return repo.getByNamr(agentName) ?: loadDefaultByName(agentName)
Note that the loadDefaultByName fun could be defined in the getConfigByAgentName method itself if needed