kotlinnull-check

Can I use `is` operator with inline variable declaration in Kotlin?


This is my first day of learning Kotlin and I have code like this:

val tagInfo : UHFTAGInfo? = rfid.readTagFromBuffer()
if (tagInfo != null) {
    val msg = hnd.obtainMessage()
    msg.obj = tagInfo
    hnd.sendMessage(msg)
}

Can I reduce it by one line by obtaining a value from rfid.readTagFromBuffer() and checking it for null?

In modern C# we can do it like this:

if (rfid.readTagFromBuffer() is UHFTagInfo tagInfo){
    val msg = hnd.obtainMessage()
    msg.obj = tagInfo
    hnd.sendMessage(msg)
}

I have tried to find answer here:

https://kotlinlang.org/docs/typecasts.html

but no success. So I assume Kotlin does not offer such feature, but maybe there is something similar that can reduce these two lines to one?


Solution

  • We can use one of scope functions e.g. let() with safe call operator:

    rfid.readTagFromBuffer()?.let { tagInfo ->
        val msg = hnd.obtainMessage()
        msg.obj = tagInfo
        hnd.sendMessage(msg)
    }
    

    ?. makes sure that let() is invoked only if the result of readTagFromBuffer() is not null and let() invokes the provided lambda passing tag info as the first argument.

    Kotlin was designed in a way that instead of introducing a lot of different features and syntaxes to solve very specific problems, we have basic and powerful building blocks like scope functions and we can use them to satisfy different kinds of needs. No need to introduce a very specific syntax for this case.