Okay, I studied the kotlin documentation, and repl.
I appreciate you taking the time.
I started talking about casts at runtime, because it was the only way I thought it could work, but in kotlin it does not work .
I failed to notice you were passing a local var in your example. Apologies.
There are situations where kotlin smart casts will not work, and code samples all fall into them.
These restrictions all make sense. You can't use implicit casts when the compiler can't guarantee the type, just as Swift requires you to provide an explicit type declaration if the inferencing system lacks the information necessary to determine the type. Also, the rules are different for local variables in both cases.
Neither fails silently. You will get a compile time error in both cases.
re: Your examples. These examples check if obj
is a String
(which would normally cause a smart cast in that context if the compiler can guarantee it can't be modified, per the rules you quoted), then immediately assign an Int
, and attempt to perform operations on obj
. This fails, as it should, because the newly assigned obj
's type is Any
and the compiler has no additional information. If you want to see a quick example of a smart cast working in the Kotlin REPL try:
fun printCount(obj:Any) {
if (obj is String) { println(obj.length) }
}
printCount("Hello")
I am a swift developer, and I'm already confused.
I'm willing to bet this is due to, as you said, you having spent more time with Swift. I'm also a Swift developer, and when I first came to Kotlin this implicit type / nullability narrowing behavior was unexpected, but as with Swift, once I understood the concept I could guess how it's going to work with a high degree of accuracy and it saved me a lot of casting and null safety checks that aren't needed. When I made a mistake, the compiler's errors were very clear. As an experienced Swift developer, it's likely you would have the same experience.
The great thing about Swift and Kotlin is that, once you get the concepts, you can usually guess how something is going to work. This is no exception. At this point I've spent a couple thousand hours with Kotlin, and I assure you, it is helpful in avoiding unnecessary type and nullability checks.
Swift goes to a lot of trouble to remove unneeded explicit type declarations. I posit this is in keeping with the language's design goals.