2016-07-07 118 views
2

在以下代码:是否可以在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) 

我们在最后一行获取下一个错误:

Error:(31, 33) Kotlin: Variable 'verticesCount' must be initialized 

Assertions.checkEnoughVertices接受一个安全型变量作为自变量(verticesCount:智力),所以verticesCount不可能在这里被初始化或为null(并且我们在这些行上没有得到相应的错误)。

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

+0

'Assertions.checkEnoughVertices'是否有一个名为'verticesCount'的参数? – marstran

+0

@marstran是的,它是这种方法的唯一参数 –

回答

4

您使用的语法表示与named arguments的函数调用,而不是局部变量的分配。所以verticesCount =只是对读者的解释,这里传递给checkEnoughVertices的值对应于名为verticesCount的那个函数的参数。它与上面声明的名为verticesCount的局部变量无关,因此编译器认为您仍然需要初始化该变量。

在科特林,分配给一个变量(a = b)是表达,所以它不能用作其它表达式的值。你必须拆分作业和while-loop条件才能达到你想要的。我会用无限循环+内部条件来做到这一点:

var verticesCount: Int 

while (true) { 
    verticesCount = consoleReader.readInt(...) 
    if (Assertions.checkEnoughVertices(verticesCount)) break 

    ... 
} 

val resultGraph = Graph(verticesCount) 
+0

这是一个相对完整和直接的解决方案。现在描述的案例对我来说很清楚。 –

+0

如何做一个“尽管”,而不是一个无限循环,然后你需要摆脱? –

相关问题