takeIf 函数内进行类型检查后进行智能转换

Héc*_*tor 2 types functional-programming casting kotlin

我有这个 Kotlin 代码:

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
}
Run Code Online (Sandbox Code Playgroud)

apply函数内部,this类型是Course?,应该是ProgrammingCourse?,不是吗?在这种情况下,智能投射不起作用。

我猜 Kotlin 还不支持这个。有没有办法让这个工作,而不使用if/else,我的意思是,以函数链接的方式?

Héc*_*tor 5

我刚刚解决了使用as?运算符,该运算符在错误时转换为ProgrammingCourse或返回null

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

现在,在apply函数内部,this类型是ProgrammingCourse(不可为空,因为?