1

In kotlin it could use ?.let to only run the code block if the variable is not null. If there are multiple variables it could be done like:

v1?.let { value1 ->
    v2?.let { value2 ->
        doSomething(value1, value2)
    }
}

compare with

if (v1 != null && v2 != null){
    doSomething(v1, v2)
}

Is there a better way to do it?

lannyf
  • 9,865
  • 12
  • 70
  • 152
  • 2
    What does "better" mean? – erip Jul 26 '23 at 13:12
  • https://stackoverflow.com/questions/35513636/multiple-variable-let-in-kotlin – david Jul 26 '23 at 13:17
  • If you use [`konad`](https://github.com/lucapiccinelli/konad), it seems like you could do something like `::doSomething.curry().on(v1.maybe).on(v2.maybe).nullable`. – erip Jul 26 '23 at 13:17

2 Answers2

1

You can make a function, pass any number of elements to it. And inside to check null or not.

fun notNull(vararg args: Any?, action: () -> Unit) {
        when (args.filterNotNull().size) {
            args.size -> action()
        }
    }

Example:

 val a = 2
 val b = "1"
 val c = "test"

 notNull(a, b, c){
           // works only when all args are not null
        }
Ivan Abakumov
  • 128
  • 1
  • 13
0

You can do something like this:

!listOf(a, b).contains(null)

Or

!listOf(a, b).any{ it == null}

But it doesn't look really good.

Louis
  • 1
  • 1