Rana Hyder
Rana Hyder

Reputation: 509

How to do comparison like greater than or less than with "Safe Casts"

In Kotlin: getting value using get without ? not acceptable. But with ? comparison not acceptable. I did search about it but couldn't find solution.

Code example

var doc = document.getData();
var v = doc?.get("curr_version");

if(v > BuildConfig.VERSION_CODE){

}

Upvotes: 1

Views: 1193

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200148

If you like the programming style with higher-order functions, I'd recommend this idiom for your code:

document.getData()
        ?.get("curr_version")
        ?.takeIf { it > BuildConfig.VERSION_CODE }
        ?.also {
           ...
        }

Upvotes: 1

Bubu
Bubu

Reputation: 1543

You can use elvis operator to return a default value if v is null like :

if (v ?: 0 > BuildConfig.VERSION_CODE)

or use ?.let { } to be sure that v is not null like :

v?.let {
    if (it > BuildConfig.VERSION_CODE) {

    }  
}

Upvotes: 1

Anton A.
Anton A.

Reputation: 1748

I will answear to)

val doc = document.getData()
doc?.let{
    if(it.get("curr_version") > BuildConfig.VERSION_CODE){
        //TODO
    }
}?:run { 
    //TODO If null
}

Upvotes: 0

yole
yole

Reputation: 97138

You can use an explicit null check:

if (v != null && v > BuildConfig.VERSION_CODE) { ... } 

Upvotes: 2

Related Questions