【问题标题】:Kotlin: Best way to express "`String?` contains `String`"Kotlin:表达“`String?` contains `String`”的最佳方式
【发布时间】:2020-05-05 18:00:02
【问题描述】:

可能只是 Use of Boolean? in if expression 的复制品,但我对 Kotlin 的了解还不够多,无法知道它是否...

我想测试body : String? 是否包含expected : String 作为子字符串。 (如果bodynull,那么它不包含子字符串。)我发现我可以这样写我的条件:

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

或者像这样:

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

(其中body?.contains(expected)Boolean? 类型的表达式),但这真的是编写这种条件的最佳最惯用 方式吗?有没有更直观的替代方案(可能使用String 的其他成员函数)?

【问题讨论】:

  • 我之所以这么问,是因为有一些像 listOfNotNull 这样的小成语在我看来是可读性的重大突破。
  • 这两个选项都没有问题,但是如果您正在寻找body 确实包含expected 的情况,第一个选项看起来更具可读性
  • 我同意@VitaliiIlchenko,我使用并看到第一个通常是因为它比第二个更具可读性。

标签: kotlin readability


【解决方案1】:

您发布的内容是默认代码检查器建议您在键入类似

时将其更改为的内容
if (body?.contains(expected) ?: false)

所以你的版本可以被认为是惯用的。

如果知道expected 不会为空,您可能会认为这样更容易阅读:

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

if (expected in body.orEmpty())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-04
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 2010-09-16
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多