Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!