What are the rules of semicolon inference?

前端 未结 3 1420
渐次进展
渐次进展 2021-02-19 00:55

Kotlin provides “semicolon inference”: syntactically, subsentences (e.g., statements, declarations etc) are separated by the pseudo-token SEMI, which stands for “

3条回答
  •  误落风尘
    2021-02-19 01:59

    I addition to Jayson Minard's answer, I've run into one other weird edge case where a semicolon is needed. If you are in a statement block that returns a function without using the return statement, you need a semicolon. For example:

    val doStuff: () -> Unit = when(x) {
        is String -> {
            { doStuff(x) }
        }
        else -> { 
            println("This is the alternate");  // Semicolon needed here
            { doNothing() }
        }
    }
    

    Without the semicolon, Kotlin thinks the { doNothing() } statement is a second argument to println() and the compiler reports an error.

提交回复
热议问题