I know I can assign a the result of an if statemen...
# getting-started
a
I know I can assign a the result of an if statement to a variable, but is there any difference between if with {} and if with () ?
a
If () without curly braces can be used with 1 line () only:
Copy code
If (value)
   //... Some code (included in the if statement)
   //... Some code (not included)
Other than that, there's no difference!
m
if you put an if/else statement without braces on one line, you can simulate the ternary operator (
* ? * : *
)
v
That's not fully correct, that is an if/else expression. 😉 I'd rather say op should give an example of what he means. Because "if with {}" vs. "if with ()" makes no sense at all, as an
if
always has
()
m
@Matteo Mirk Did Kotlin add a ternary operator?
v
No
They have the if-expression, so don't feel the need to add another syntax for the same logic
m
yeah sorry bad wording: if expression, because it’s assignable in K
v
If it has an
else
, yes. Without it should actually be statement I think. 🙂
m
sure sure, I’m just towards the working day and my mind has gone jelly… 😄
a
Okay, I mean:
Copy code
val max = if (a > b) (
        a
) else (
    b
)
vs
Copy code
val max = if (a > b) {
    a
} else {
    b
}
But now from your previous response I’m seeing that it’s just that it happens to work when it’s only one line, not because of the () but because it’s okay that there aren’t any {}
v
Exactly, if there is only one expression you don't need curly braces. Whether you have round brackets there or not is totally irrelevant, you can also leave them out and and all is exactly the same, just syntactic variances.
a
yeah, thanks! For some reason my brain discarded the easy answer and went into: what is this very obscure different if 😂
m
@acoconut Wow I missed this out completely… I couldn’t imagine you meant such a use! Where did you see such formatting or did you come up with it?
v
I feared he meant that, that's why I asked for an example 😄
m
I couldn’t see it coming haha
a
Honestly I started a new job and I use to do Java but they do Kotlin here and I’m trying to learn from the codebase, so I guess I either saw something like that or I’m here throwing stuff together to see if it compiles and did it by myself 😂
m
Hehe I know what you mean, it was fun to see it because when you’re so used to a certain style you don’t think that it’s possibile to write code creatively
😅 3