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.
text.orEmpty()
text.orEmpty()
for a String?
will return "" if null, or the original string
The best alternate option is text ?: ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With