Quuxplusone
Quuxplusone

Reputation: 27210

Kotlin: Best way to express "`String?` contains `String`"

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?

Upvotes: 1

Views: 1336

Answers (1)

Tenfour04
Tenfour04

Reputation: 93659

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())

Upvotes: 5

Related Questions