https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
d

David Rodrigues

08/13/2022, 10:06 PM
I've been thinking of a practical way to
return
a certain value based on a condition, and I'd like to propose this feature:
Copy code
return x if != null
// <and/or>
return x if user != null
Same for
break
or
continue
Other examples:
Copy code
return x if >= 5
return x if is User
return x if x + 1 >= 5
And maybe:
Copy code
x = 5 if x < 2
3
🚫 2
j

jw

08/13/2022, 10:19 PM
Not sure if parenthesis are required to disambiguate some edge case, but regardless it's the same number of characters to do
if (user != null) return x
and it means you're aware of the conditional before seeing the action.
d

David Rodrigues

08/13/2022, 10:22 PM
I don't know if it's a matter of my language (Portuguese), but it sounds better to me to say something like "return X if it is greater than 5" than "if X is greater than 5, return X itself". My suggestion was more towards code style and readability, but I don't know if it applies to everyone.
f

Fleshgrinder

08/14/2022, 6:42 AM
It's correct English in both cases and both sound good. What does it return if the condition is not true? Null? Unit? This is basically where the current way shines, you have to have the else and there is nothing implicit.
Copy code
return if (x is User) x else null
h

hfhbd

08/14/2022, 6:43 AM
There was a similar request a few months ago, and I think the order is confusing. At the moment, you read and execute from left to right, reading follows code execution, first condition, then its value/expression. To understand the new syntax, you must read the condition first and then the value/expression. Reading does not follow the code execution. With complex expression, this is harder to understand, especially for a newcomer, I guess.
2
f

Fleshgrinder

08/14/2022, 6:47 AM
Python has it all over and it's probably the most successful language among non programmers. If all of these people get it, well... 😉 The implicitness and the totally different syntax (no parentheses) are much more problematic in the context of Kotlin since this syntax has no precedence anywhere else and thus makes both the compiler and the language harder overall. This is actually true for Python. It is very inconsistent in how you have to write things at times.
1
k

Klitos Kyriacou

08/15/2022, 8:37 AM
Richard Fussenegger:
What does it return if the condition is not true? Null? Unit?
I understood the OP as meaning that it doesn't return if it's not true. It carries on, same as
if (x is User) return x
without an
else
part. I'm neither for nor against this proposition, but found it interesting as similar syntax appears in various other languages.
1
3 Views