The unsafe cast in Kotlin is done by the infix operator as. Usually, the cast operator throws an exception if the cast isn't possible. Var properties - never, because the variable can be modified at any time by other code. Var local variables - if the variable is not modified between the check and the usage, is not captured in a lambda that modifies it, and is not a local delegated property. Smart casts cannot be used on open properties or properties that have custom getters. Val properties - if the property is private or internal or if the check is performed in the same module where the property is declared. Val local variables - always, with the exception of local delegated properties. If you try, Android Studio will notify you of an error, and the Kotlin compiler will throw an error in your build. More specifically, smart casts can be used under the following conditions: The Nullable annotation ensures that when using the result of getCurrentName in a Kotlin file, you can’t dereference it without a null check. Note that smart casts work only when the compiler can guarantee that the variable won't change between the check and the usage.
0 Comments
Leave a Reply. |