Swift 'if let' statement equivalent in Kotlin

前端 未结 14 1962
心在旅途
心在旅途 2020-12-02 07:32

In Kotlin is there an equivalent to the Swift code below?

if let a = b.val {

} else {

}
14条回答
  •  误落风尘
    2020-12-02 08:13

    I'm adding this answer to clarify the accepted answer because it's too big for a comment.

    The general pattern here is that you can use any combination of the Scope Functions available in Kotlin separated by the Elvis Operator like this:

    ?. {
        // code if not null
    } :?  {
        // code if null
    }
    

    For example:

    val gradedStudent = student?.apply {
        grade = newGrade
    } :? with(newGrade) {
        Student().apply { grade = newGrade }
    }
    

提交回复
热议问题