小编And*_* K.的帖子

是否可以在 Kotlin 的 while 条件体中初始化一个变量?

在下面的代码中:

    var verticesCount: Int // to read a vertices count for graph

    // Reading until we get a valid vertices count.
    while (!Assertions.checkEnoughVertices(
            verticesCount = consoleReader.readInt(null, Localization.getLocStr("type_int_vertices_count"))))
        // The case when we don't have enough vertices.
        println(String.format(Localization.getLocStr("no_enough_vertices_in_graph"),
                              Assertions.CONFIG_MIN_VERTICES_COUNT))

    val resultGraph = Graph(verticesCount)
Run Code Online (Sandbox Code Playgroud)

我们在最后一行收到下一个错误:

Error:(31, 33) Kotlin: Variable 'verticesCount' must be initialized
Run Code Online (Sandbox Code Playgroud)

Assertions.checkEnoughVertices接受一个安全类型变量作为参数 (verticesCount: Int),因此这里 verticesCount 不可能未初始化或为空(并且我们在这些行上没有得到相应的错误)。

当已经初始化的变量再次未初始化时,最后一行发生了什么?

while-loop variable-initialization kotlin

3
推荐指数
2
解决办法
2240
查看次数