Legend123
Legend123

Reputation: 378

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?

Upvotes: 0

Views: 331

Answers (1)

IR42
IR42

Reputation: 9672

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() }

Upvotes: 1

Related Questions