Search code examples
kotlinkotlin-extension

Create extension that run a function if object is not null


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 }

Solution

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