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?

3
  • I ask because there are little idioms like listOfNotNull that turned out to be big breakthroughs in readability, for me. Commented May 5, 2020 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 Commented May 5, 2020 at 18:10
  • I agree with @VitaliiIlchenko, I use and see the first one usually because it's more readable than the second. Commented May 5, 2020 at 18:28

1 Answer 1

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.