I want to execute two functions on the same line w...
# getting-started
r
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
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
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
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
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
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
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
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
also I would recommend avoiding lines that start with a bare
{
, because of how easily that could be interpreted as a lambda in Kotlin