Reputation: 624
Can I have kotlin extension function that do something like this:
// extension
inline fun <T : Any> T?.runIfNotNull(function: (T) -> Unit) {
this?.let { function(it) }
}
// some function
fun doSomething(int: Int){
// do something
}
// doSomething will be called with maybeNullInt as argument,
// when maybeNullInt is not null
maybeNullInt?.runIfNotNull { doSomething }
basically, what I want is replace
maybeNullInt?.let{ doSomething(it) }
with
maybeNullInt?.runIfNotNull { doSomething }
Upvotes: 1
Views: 296
Reputation: 170805
basically I want to do this maybeNullInt?.runIfNotNull { doSomething }
You already can with ?.let
(or ?.run
):
maybeNullInt?.let(::doSomething)
You can't write { doSomething }
because it would mean something quite different. See https://kotlinlang.org/docs/reference/reflection.html#callable-references for explanation of the ::
syntax.
If you define runIfNotNull
you can actually use it without ?
:
maybeNullInt.runIfNotNull(::doSomething)
(does nothing if maybeNullInt
is null
).
Upvotes: 4
Reputation: 30685
Instead of creating your own extension function you can use let
function from Kotlin Standard Library:
maybeNullInt?.let(::doSomething)
::
- in Kotlin we use this operator to reference a function by name.
Upvotes: 5
Reputation: 1107
Yes you can.
Either use function reference
maybeNullInt?.runIfNotNull(::doSomething)
or pass a parameter in a lambda
maybeNullInt?.runIfNotNull { doSomething(it) }
Upvotes: 1