1

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 }
Sergio
  • 27,326
  • 8
  • 128
  • 149
SIRS
  • 624
  • 6
  • 20
  • Why do you need additional function if you can use for example `maybeNullInt?.let{}`? – Sergio Mar 16 '19 at 06:32
  • basically I want to do this `maybeNullInt?.runIfNotNull { doSomething }` not this `maybeNullInt?.let{ doSomething(it) }` – SIRS Mar 16 '19 at 07:02

3 Answers3

5

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.

Sergio
  • 27,326
  • 8
  • 128
  • 149
4

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).

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
1

Yes you can.

Either use function reference

maybeNullInt?.runIfNotNull(::doSomething)

or pass a parameter in a lambda

maybeNullInt?.runIfNotNull { doSomething(it) }
uaraven
  • 1,097
  • 10
  • 16