hey, I have a repository that returns a nullable o...
# getting-started
p
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
you could make use of an extension funktion with nullable receiver
p
like what?
i ended up with something like this:
Copy code
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
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