Home > Net >  Is return inside function definition is also a expression in kotlin
Is return inside function definition is also a expression in kotlin

Time:03-21

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 ?

CodePudding user response:

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.

  • Related