Héctor
Héctor

Reputation: 26034

Smart cast after type check inside takeIf function

I have this Kotlin code:

interface Course
class ProgrammingCourse : Course
class MathCourse : Course

...

fun doSomething(id: String) = getCourse(id)
    .takeIf { it is ProgrammingCourse }
    .apply {
      //do something with the course
    }
}

fun getCourse(id: String) : Course {
    //fetch course
}

Inside apply function, this is of type Course?, it should be ProgrammingCourse?, isn't it? Smart cast is not working in this case.

I guess Kotlin doesn't support this yet. Is there a way to make this work, without using if/else, I mean, in a function chaining way?

Upvotes: 2

Views: 585

Answers (1)

Héctor
Héctor

Reputation: 26034

I have just solved using as? operator, that casts to ProgrammingCourse or returns null on error:

fun doSomething(id: String) = getCourse(id)
    .let { it as? ProgrammingCourse }
    ?.apply {
      //do something with the course
    }
}

Now, inside apply function, this is of type ProgrammingCourse (non-nullable, because of ?)

Upvotes: 5

Related Questions