基于Kotlin coding conventions,不建议将花括号放在自己的行上,因为分号是可选的,并且可能导致令人惊讶的行为。如果我们将开括号放在自己的行上,会出现令人惊讶的行为吗?
Formatting
In most cases, Kotlin follows the Java coding conventions.
Use 4 spaces for indentation. Do not use tabs.
For curly braces, put the opening brace in the end of the line where the construct begins, and the closing brace on a separate line aligned horizontally with the opening construct.
if (elements != null) { for (element in elements) { // ... } }
(Note: In Kotlin, semicolons are optional, and therefore line breaks are significant. The language design assumes Java-style braces, and you may encounter surprising behavior if you try to use a different formatting style.)
最佳答案
关于令人惊讶的行为的评论不是关于大括号,而是更笼统的。考虑以下代码:
val result = 1
+ 2
println(result)
您可能希望它显示“3”,但它显示“1”,因为这是2条语句,
val result = 1
和+ 2
如果您想打破界限,可以在Kotlin中这样写:
val result = 1 +
2
这是一个简单的示例,但突出了没有分号来确定语句结尾的区别。
关于kotlin - 在Kotlin的换行符中打开花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56909503/