【问题标题】: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() }