Kotlin idiom for working with non-null object and non-blank String representation

Viewed 1701

I have a nullable property (a Java object) that knows how to convert itself to a String, and if this representation is not empty, I would like to do something with it. In Java this looks like:

MyObject obj = ...
if (obj != null) {
    String representation = obj.toString();
    if (!StringUtils.isBlank(representation)) {
        doSomethingWith(representation);
    }
}

I'm trying to find the most idiomatic way of converting this to Kotlin, and I have:

    with(obj?.toString()) {
        if (!isNullOrBlank()) {
            doSomethingWith(representation)
        }
    }

But it still feels like too much work for such a simple operation. I have this feeling that combining let, when, and with I can slim this down to something a bit shorter.

The steps are:

  1. If the object (A) is not null
  2. If the String representation (B) of object (A) is not blank
  3. Do something with (B)

I tried:

    when(where?.toString()) {
        isNullOrBlank() -> builder.append(this)
    }

But (1) it fails with:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: @InlineOnly public inline fun 
 CharSequence?.isNullOrBlank(): Boolean defined in kotlin.text @InlineOnly public inline fun CharSequence?.isNullOrBlank(): Boolean defined in 
 kotlin.text

And even if it got past that, (2) it would want the exhaustive else, which I don't really care to include.

What's the "Kotlin way" here?

1 Answers
Related