是否有可能在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:Int),所以verticesCount不可能是未初始化的,或者在这里是空的(我们没有在这些行上得到相应的错误)。

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

您使用的语法表示具有命名参数的函数调用,而不是指定局部变量。 所以verticesCount =只是给读者一个解释,在这里传递给checkEnoughVertices对应于名为verticesCount的那个函数的参数。 它与上面声明的名为verticesCount的局部变量无关,所以编译器认为你还是要初始化那个变量。

在Kotlin中,赋值给变量( a = b不是一个表达式,所以它不能作为其他表达式的值。 你必须分配任务和while循环条件来达到你想要的。 我会做一个无限循环+里面的一个条件:

 var verticesCount: Int while (true) { verticesCount = consoleReader.readInt(...) if (Assertions.checkEnoughVertices(verticesCount)) break ... } val resultGraph = Graph(verticesCount) 
Interesting Posts