homelessDevOps
homelessDevOps

Reputation: 20726

Kotlin "no cast needed" in IDE

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:

Both functions are defined as (Gradle-Plugin):

fun Exec.XX() 

Upvotes: 2

Views: 797

Answers (1)

gidds
gidds

Reputation: 18607

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

Upvotes: 4

Related Questions