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

172
Visualizações
Is return inside function definition is also a expression in kotlin
fun trueOrFalse(exp: Boolean): String { 
  if (exp) return "It's true!" 
  return "It's false"            
}

I was reading the "atomic kotlin" book where it says this function contains 2 expression so I just wanted to is function return also expression in kotlin ?

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

0

Unlike most programming languages, Kotlin treats return ... not as a statement but as an expression.

The type that the compiler infers for such expressions is Nothing, which means that the expression never evaluates to anything, and the control flow never continues normally after such an expression (similar to throw-expressions).

An example that demonstrates that it's an expression would be:

val x = when (coin) {
    0 -> 123
    1 -> (return 456) as Nothing
    else -> error("unexpected coin value")
}

(runnable sample)

With the type of a return ... expression being Nothing, it doesn't make a lot of sense to use it as a part of other composite expressions. However, there are cases when it's convenient:

  • val x = if (foo) bar() else return baz()
  • val x = foo() ?: return bar()

Fun fact: expressions like return return return 5 are valid, although they trigger a compiler warning for unreachable code.

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