kotlin - 在Kotlin的换行符中打开花括号

标签 kotlin

基于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/

相关文章:

android - Realm Android javassist.NotFoundException : io. realm.com_example_realmtest_data_SomethingRealmProxyInterface

android - 防止在 BottomNavigationView 中快速单击

kotlin - Kotlin FlatMap &&递归

android - 如何使用 Retrofit 库将 X-API-Key 和 X-Session 添加到 header ?

Android:从 kotlin 合成迁移到数据绑定(bind)后无法切换可见性

android - 如何自定义Mapbox路线的样式?

android - 如何防止在我的 flutter 应用程序的特定部分截屏?

android - 我对项目中每个项目的适配器定位有疑问

android - 未能通过androidX错误进行构建,但我未在项目中使用androidX

android - 如何在Android的外部浏览器中读取PDF文件