【问题标题】:Kotlin - How to call nullable method with receiver only if it exists?Kotlin - 如何仅在接收器存在时才使用接收器调用可为空的方法?
【发布时间】:2021-04-16 20:21:09
【问题描述】:

我有一个函数接受Article 和可空方法,Article 作为其接收者。我想调用可为空的方法并仅在它存在时才返回其结果。我该怎么做?

fun foo(article: Article, method: (Article.() -> String)? = null): String? =
    article?.method() // how can I do this?

【问题讨论】:

    标签: function kotlin lambda nullable receiver


    【解决方案1】:
    fun foo(article: Article, method: (Article.() -> String)? = null): String? =
        method?.invoke(article)
    

    fun foo(article: Article, method: (Article.() -> String)? = null): String? =
        method?.let { article.it() }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 2020-06-13
      相关资源
      最近更新 更多