Kotlin: Why can't I do an assignment in a loop guard?
Answer #1 100 %The syntax is not valid, because c = reader.read()
is not an expression in Kotlin ? this prevents all the ==
vs =
bugs.
You have to rewrite it as:
while (true) {
val c = reader.read()
if (c == 1) break
...
}
Answer #2 100 %Note: The other answer explains the problem with your syntax, here is an alternative to using the while
loop.
A great thing about Kotlin is that you can change your own world to be exactly the way you want it. So let's create an extension function to do what basically is in the other answers, but making it more appealing.
With this extension function:
inline fun Reader.readWhile(crossinline predicate: (Int) -> Boolean): Sequence {
return generateSequence {
val c = this.read()
if (c != -1 && predicate(c)) {
c.toChar()
} else {
null
}
}
}
You can now simply:
reader.readWhile { it != 1 }.forEach {
// do something with each char
}
And if you want to auto close the reader:
reader.use {
reader.readWhile { it != 1 }.forEach {
// do something with each char
}
}
And of course you decide if the sequence is of Char
or Int
depending on your needs. You could create your own useChars
or forEachChar
or whatever makes your code the way you want it to be. Look at the Kotlin API Refrence for kotlin.io for examples of other extensions, especially on Reader
for ideas.
Unit Test
A unit test for the extension function:
@Test fun testSo32596261() {
val reader = CharArrayReader(charArrayOf('A', 'B', 'C', 1.toChar(), 'D', 'E', 'F'))
reader.use {
assertEquals(listOf('A', 'B', 'C'), reader.readWhile { it != 1 }.toList())
}
}