9

How can I check if lambda is empty in Kotlin? For example, I have signature like

onError:(Throwable) -> Unit = {}

How can I differ is its default value comes to body or value applied to this function?

Sunstrike
  • 456
  • 1
  • 6
  • 22

3 Answers3

17

You couldn't test if the body of an lambda is empty (so it contains no source-code) but you can check if the lambda is your default value by creating a constant for that value and use this as default value. Than you can also check if the value is the default value:

fun main(args: Array<String>) {
    foo()
    foo { }
    foo { println("Bar") }
}

private val EMPTY: (Throwable) -> Unit = {}
fun foo(onError: (Throwable) -> Unit = EMPTY) {
    if (onError === EMPTY) {
       // the default value is used
    } else {
       // a lambda was defined - no default value used
    }
}
guenhter
  • 11,255
  • 3
  • 35
  • 66
  • 1
    This checks if the user passed a lambda, not if the lambda is empty. – CLOVIS Aug 13 '22 at 15:21
  • Yes you are right. Even if the original question asked about "empty lambda" the intention of the question was, to see if the user applied a function (be it empty or not) or if the default (empty lambda) was used. – guenhter Aug 18 '22 at 12:00
4

Just don't use empty lambdas as defaults.

Since in kotlin nullability is a first class citizen and the clear indication of a missing value, I would pass null as the default argument.

onError: ((Throwable) -> Unit)? = null

The signature looks a bit ugly, but I think it's worth it.

For example it can be easily checked and handled and you don't expect that the lambda does something useful - especially for lambdas with a return value.

I gave the same comment here: https://stackoverflow.com/a/38793639/3917943

Mathias Henze
  • 2,190
  • 1
  • 12
  • 8
0

I don't believe there is a way to check if a lambda contains executable code or not (at least not to my knowledge), but you could do something like the following:

fun foo(onError: ((Throwable) -> Unit)? = null) {
    if (onError != null) {
        // do something
    } else {
        // do something else
    }
}
kc_dev
  • 578
  • 1
  • 6
  • 21