1

This might be simply a duplicate of Use of Boolean? in if expression, but I don't know enough Kotlin to know whether it is...

I want to test whether body : String? contains expected : String as a substring. (If body is null, then it doesn't contain the substring.) I've figured out that I can write my condition like this:

    if (body?.contains(expected) == true) {
        succeed()
    }

or like this:

    if (body?.contains(expected) != true) {
        fail()
    }

(where body?.contains(expected) is an expression of type Boolean?), but is that really the best or most idiomatic way of writing such a condition? Are there any alternatives (possibly using other member functions of String) that are easier on the eyes?

Quuxplusone
  • 23,928
  • 8
  • 94
  • 159
  • I ask because there are little idioms like [`listOfNotNull`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/list-of-not-null.html) that turned out to be big breakthroughs in readability, for me. – Quuxplusone May 05 '20 at 18:01
  • there is nothing wrong with both options but the first one looks a bit more readable if you are looking for the case when `body` does contain `expected` – Vitalii Ilchenko May 05 '20 at 18:10
  • I agree with @VitaliiIlchenko, I use and see the first one usually because it's more readable than the second. – Giorgio Antonioli May 05 '20 at 18:28

1 Answers1

5

What you posted is what the default code inspector recommends you change it to if you type something like

if (body?.contains(expected) ?: false)

so your version can be considered idiomatic.

If it's known that expected will not be empty, you might consider it easier to read like this:

if (body.orEmpty().contains(expected))

or

if (expected in body.orEmpty())
Tenfour04
  • 83,111
  • 11
  • 94
  • 154