Kotlin "no cast needed" in IDE

Viewed 397

I'am new to Kotlin (and Java) so may be a stupid question, but IntelliJ keeps telling me "No cast needed" on the second function call. If i switch the order of the functions the same for the other functions.

I could imagine 2 things:

  • Kotlin is smart it knows: Hey first cast is fine, so i will cast the second

  • IntelliJ problem ?

    (this as Exec).setVersionToDeploy()
    (this as Exec).setEcsTaskMemory()
    

Both functions are defined as (Gradle-Plugin):

fun Exec.XX() 
1 Answers

Your first guess is correct!

This is known as a smart cast: the compiler knows that, if execution reaches your second line, the type of this must be Exec (else the first line would have thrown a ClassCastException and it wouldn't have reached the second line).  So it infers the specific type, and a further cast is not needed

In general, the compiler infers types in cases such as this, so you don't need to cast explicitly.  (It's not an error to do so, only a warning; but IDEA is very keen on showing ways your code can be improved.)

You see this most commonly with nullability (since that's part of the type system).  For example, if you have a nullable field, the compiler won't let you call its methods directly:

val myString: String? = "abc"
println(myString.length) // COMPILE ERROR, as myString could be null

but if you add a manual check, the compiler smart-casts the field to its non-nullable type, so you don't need a cast:

val myString: String? = "abc"
if (myString != null)
    println(myString.length) // OK; compiler infers type String
Related