Kotlin - 如何仅在接收者存在时调用可为空的方法?
Kotlin - How to call nullable method with receiver only if it exists?
我有一个函数接受 Article
和可空方法,并以 Article
作为接收者。我只想调用可为 nullable 的方法,并且 return 仅当它存在时才调用它的结果。我该怎么做?
fun foo(article: Article, method: (Article.() -> String)? = null): String? =
article?.method() // how can I do this?
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() }
我有一个函数接受 Article
和可空方法,并以 Article
作为接收者。我只想调用可为 nullable 的方法,并且 return 仅当它存在时才调用它的结果。我该怎么做?
fun foo(article: Article, method: (Article.() -> String)? = null): String? =
article?.method() // how can I do this?
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() }