https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ray Rahke

02/21/2024, 8:36 PM
I want to execute two functions on the same line within a conditional block without using curly braces.
This results in the unintended behavior of
c()
always being executed as the
;
breaks it outside of the else, despite them being on the same line.
are there any alternatives. I thought of doing
Copy code
else
    b() && c()
but this only works for boolean functions
c

Casey Brooks

02/21/2024, 8:39 PM
Yes, this is correct. Kotlin doesn’t have significant whitespace like other languages, so there’s no inherent relation between two statements on the same line. The important bit is the statement, not the line. An if/else block without curly braces evaluates the next statement for the conditional, not the next line
r

Ray Rahke

02/21/2024, 8:39 PM
Was just wondering if there were any syntactical tricks i could use to get this to work
I know it is a weird want but I am really really fond of braceless, singleline if statements.
c

Casey Brooks

02/21/2024, 8:40 PM
Just throw braces around the lines (you can do it on the
else
without needing them on
if
)
Copy code
if (condition)
    a()
else
    { b(); c() }
r

Ray Rahke

02/21/2024, 8:40 PM
else _b_(), c() comma doesn't work 😕
heh yeah, but at that point I might as well do a normal braced else
well
it doesnt take up the last line so that is better I guess
thanks
e

ephemient

02/21/2024, 8:45 PM
in principle you could
Copy code
fun run(vararg blocks: () -> Unit) {
    for (block in blocks) block()
}
if (condition) a() else run(::b, ::c)
but your initial code is already not common Kotlin style as far as I've seen, which is that multiline always uses braces
r

Ray Rahke

02/21/2024, 8:48 PM
yeah. i just think when the executions are quite short it is easier on the eyes to have them horizontally adjacent on one line
and then the braces just add visual noise since it's only 1 line long
not a big deal
j

Jeff Lockhart

02/21/2024, 10:34 PM
You might reconsider your aversion to curly braces when you consider the potentially serious consequences of such a bug that's easy to introduce by not using them. It makes the scope explicit when using multiple lines.
3
e

ephemient

02/21/2024, 10:35 PM
also I would recommend avoiding lines that start with a bare
{
, because of how easily that could be interpreted as a lambda in Kotlin