Smart cast to 'Type' is impossible: how to fix error in Kotlin with mutable properties?
Hi everyone! I'm new to Kotlin and encountered a confusing error. I have a class with a mutable property `var`, and I'm trying to perform a type check using `is`, but the compiler says: "Smart cast to 'String' is impossible, because 'name' is a mutable property that could have been changed by this time".
Here's my code:
```kotlin
class User {
var name: Any = "John"
fun printName() {
if (name is String) {
// Error here: Smart cast to 'String' is impossible
println(name.length)
}
}
}
```
I understand that `name` is a `var`, but I checked its type before using it! Why doesn't the compiler trust me? How do I fix this? In Java with `instanceof` check there was no such problem. Maybe I'm missing something in Kotlin basics?
No answers yet.
Log in to leave an answer