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