简体   繁体   中英

Kotlin - How to call nullable method with receiver only if it exists?

I have a function that accepts an Article and nullable method with Article as its receiver. I want to call the nullable method and return its results only if it exists. How can I do this?

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)

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM