Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set non-null string variable's value to empty if null value passed

Tags:

kotlin

How can I achieve this java code's analog in Kotlin?

class Item {
    private String text = "";

    public String getText() {
        return text;
    }

    public void setText(String str) {
        if(str == null){
            text = "";
        } else {
            text = str;
        }
    }

}

So whenever I set null value for text, it's value replaced with empty string. I want exactly the same behavior but in Kotlin, because I'm working with Java classes in Kotlin code, which may return some null values. Checking for nullability everytime before setting fields value is not a good idea, because it can be forgotten by accident, and give an exception at runtime.

like image 356
Nur4I Avatar asked Oct 19 '25 05:10

Nur4I


1 Answers

The simplest way is text.orEmpty()

text.orEmpty() for a String? will return "" if null, or the original string

The best alternate option is text ?: ""

like image 87
Gibolt Avatar answered Oct 21 '25 01:10

Gibolt



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!