Hi everyone :slightly_smiling_face: Does anyone kn...
# getting-started
j
Hi everyone 🙂 Does anyone know why in intellij IDEA there is no autocomplete for
readText
even after the cast in the line above?
Copy code
for (frame in incoming) {
                frame as? Frame.Text ?: continue
                val receivedText = frame.readText() // No autocomplete here
                send("You said: $receivedText")
            }
I'm going through the KTOR creating web socket chat tutorial and thought it was broken because it didn't give autocomplete for
readText
. It would only give
readBytes
for a general
Frame
.
Interestingly, it seems like it only happens when I don't bind the result to a variable. The following code works just fine and gives autocompletion as expected.
Copy code
for (frame in incoming) {
                val f = frame as? Frame.Text ?: continue
                val receivedText = f.readText()
                send("You said: $receivedText")
            }
e
https://kotlinlang.org/docs/typecasts.html#smart-casts
Note that smart casts work only when the compiler can guarantee that the variable won't change between the check and the usage.
although
for (frame in
should count as a local
val
bind, so that's strange…
j
That's what I was thinking 😅 But apparently using the
is
keyword works as expected as well
Copy code
for (frame in incoming) {
                if (frame !is Frame.Text) continue
                val receivedText = frame.readText()
                send("You said: $receivedText")
            }
k
I presume the Kotlin compiler recognises the smart cast in your original example, since
frame.readText()
is not a compilation error, but just no autocomplete. Therefore it looks like an IntelliJ bug.
👍 1