Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null and Empty check using Elvis Operator

Tags:

kotlin

I have:

return if(mValue== null || mValue.asString.isNullOrEmpty()) "Home" else mValue.asString

I tried to perform Elvis operator:

return mValue?.asString ?: "Home"

But I also want to check for empty case for mValue as well.

So if mValue is either null or if it's empty, I want to return "Home" else return its content in String, without using when or if.

Thank you!

like image 997
Humble Hermit Avatar asked Jul 15 '26 02:07

Humble Hermit


2 Answers

You cannot actually use elvis operator for the case if the String is empty. According to documentation elvis operator is only used to check whether a variable is null or not. Therefore, I would suggest you using:

return if (mValue.isNullOrEmpty()) "Home" else mValue

Hope it helps!

like image 197
Ilya Maier Avatar answered Jul 17 '26 16:07

Ilya Maier


You could combine orEmpty and ifEmpty:

return mValue?.asString.orEmpty().ifEmpty { "Home" }

Whether that's an improvment or not, I don't know.

like image 40
Michael Avatar answered Jul 17 '26 15:07

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!