Search code examples
androidnullkotlinwarningskotlin-null-safety

Kotlin Null safety warning Unexpected tokens (use ; to seperate expressions on the same line)


I was trying Elvis operator in Kotlin code in my application and received following warning:

Unexpected tokens (use ; to seperate expressions on the same line)

Code:

    var key: String = "KEY is"
    /* "check" is name of String variable which can be null
    Warning coming on following statement*/
    var str : String = check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check

Any ideas how to resolve this?


Solution

  • I would not understand why you need any null safe operators here. None of your variables are nullable.


    You wrote

    check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check
    

    ? (after check) is not an operator in Kotlin.

    You may have wanted the ternary conditional operator, which is simply replaced by if/else.

    Judging from your comment, you seem to want the safe call operator though, which is ?., not ?.

    check?.key?.replace("KEY", "ABDS-ASDSA-DSSS") ?: check
    

    There is a difference between the Elvis operator and the safe call operator. The Elvis operator works with an expression while the safe call operator is simply a null-safe property access or method call.

    The Elvis operator returns its first operand if it is not null, and returns the second operand otherwise.

    The ?. operator returns null if the receiver is null, otherwise, it returns the result of the call.