Hey, What about removing unnecessary parenthesis in conditions?
Which is more readable?:
if (x == 5) {
println!(“x is five!”)
} else {
println!(“x is not five”)
}
vs
if x == 5 {
println!(“x is five!”)
} else {
println!(“x is not five”)
}
Go started using this kind of syntax first and many modern programming languages like Rust, Swift adopted it. What about avoiding parenthesis for conditions and loops in Kotlin? Don’t we have a good IDE that can clearly show conditions and loops without these unnecessary parenthesis?
if this is SimpleCondition || hasNoBranches() println("Parenthesis aren't critical") else if this is ComplexCondition || hasMultipleBranches() println("Parenthesis are very helpful")
The OP suggested removing unnecessary parentheses, and you additionally removed curly brackets as well for some reason. I’m also not sure how often you should be writing nested, single-line if-else expressions like that.
“Necessity” is a subjective notion. That is Jess can decide that all parens aren’t necessary because can read any conditional expression anyway. But will such code be readable for James?
But we can go beyond. Kotlin already has following control structure: when { x == 5 -> println("x is five!") else -> println("x is not five") }
Why not just: x == 5 -> println("x is five!") else -> println("x is not five")
Considering -> as some kind of postfix if
I often feel frustrated at having to type in the parenthesis and have wished many times they weren’t there. But when I think of code like above, it makes me reconsider.
As to another response suggesting that the parenthesis should be optional only conditionally, I think that makes it even harder because the writer / reader have to think of that condition every time they write an if.
Not suggesting one can’t do away with the parenthesis. But might need something to specify where the if condition ends and the block begins.
All of the languages you’ve listed require you to use curly braces in if statements. In Kotlin, curly braces are optional because requiring them would make single-line if expressions (Kotlin’s replacement for the ternary operator) too ugly. And making both curly braces and parentheses optional will inevitably lead to ambiguities. Therefore - no, in Kotlin those parentheses are not unnecessary and cannot be removed.
Scala allows similar in pattern guards, eg, case x if x == 2 => and I find that its much nicer to read over case x if (x ==2) =>. It would be nice to do something similar in very simple if statements, it doesn’t have to work for complicated if statements.
Personally, I’d like it to go the Python way but it’s too late for THAT drastic of a syntax change
I’m fine with parens in a language like Kotlin. It fits the style.