Conditional Return

Hey,

what are your thoughts on proposing a not-null-conditional return statement.

Take this example:

fun findAccount(search: String): Account? {
  search.toLongOrNull()?.let { id ->
    findAccountByID(id)?.let { return it }
  }
  findAccountByUsername(search)?.let { return it }
  findAccountByEmail(search)?.let { return it }
  return null
}

This function tries different methods to find an entity, and returns null if none match. With the syntax I am thinking of, you could rewrite the above snippet to this:

fun findAccount(search: String): Account? {
  return? search.toLongOrNull()?.let { findAccountByID(it) }
  return? findAccountByUsername(search)
  return? findAccountByEmail(search)
  return null
}

return? would then only actually return if the returned value is not null, i.e. the compiler could
transform return? $1 to if ($1 != null) return $1.

P.S. I know this is a bad way of searching for an entity, this is just an example.

1 Like

Seems you can achieve the same by chaining a bunch of elvises operators:
return contionA() ?: conditionB() ?: ...

Isn’t it basically the same that you can achieve using elvis operator?

fun findAccount(search: String): Account? {
    return search.toLongOrNull()?.let { findAccountByID(it) }
        ?: findAccountByUsername(search)
        ?: findAccountByEmail(search)
}

Main difference is, that this is a bit less flexible than what you propose, because it’s a single expression, so you could not easily mix it with other code.
On the other hand, I don’t see obvious use cases for such mixing.

Admittedly, in this very example, the elvis operator would probably be enough. I was more thinking of larger functions, which may have more code after a conditional return.

On a second thought, however, I am not sure if the idea of having executed code after a return, even if it’s just return?, is that clever. It might make the code more difficult to read, so I guess a normal if statement, or other methods, are sufficient.

Just wanted to hear some opinions from the community.

1 Like

We have seen such feature requests before, one for nullable return (KT-8268) and one for nullable throw (KT-46106) operators.

It seems that the common intuition is to place ? after an operator to indicate that its execution depends on the argument being not null. However, this behavior is not typical for ? in Kotlin. Usually the term that is to the left from ? is nullable, and the term that is to the right is evaluated depending on the actual nullability of the term to the left. This proposal reverses these roles. So, we’re considering alternative syntactic options that would be more consistent with the existing practice of using ? in Kotlin.

1 Like

Could this method also be written using a when statement? The first clause is the most complex, but it could still work.