Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Koltin return null if value is null else

I work with some business logic written in Kotlin. I've got such a case in my method - I check a value for null, and if it IS null - I want to return null, else do some logic. My version looks like:

fun calculateFoo(parameter: SomeObject?): ReturnObject? = 
    if (parameter == null) null
    else performCalculation(parameter)

Literally "If value is null then return itself else process it". Normally, we do something if value is NOT null, like elvis operator, but here is "reversed" logic. Is there a better solution for this?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Taking a step back, if you make this an extension function with non-null parameter, it leads to more natural use at its call site.

fun SomeObject.calculateFoo(): ReturnObject = 
    performCalculation(this)


val nullable: SomeObject? = ...
val result = nullable?.calculateFoo()

I think it's better for code clarity for a function not to simply return null for a null argument, because it masks nullability at the call site, where a ?. call would suffice and keep the code clear about the possible null return value. The semantics of your function as-is allow a useless argument to be passed for a useless result.

Granted, I understand your example is contrived, and there are cases where there are multiple arguments or where a null argument only leads to a useless result under certain circumstances, in which case the ?.let answer would be more appropriate.

over 4 years ago · Santiago Trujillo Relatório

0

You can use the ?. operator in combination with let.

fun calculateFoo(parameter: SomeObject?): ReturnObject? = 
    parameter?.let { performCalculation(it) }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda