Kotlin ?.let + ?:run + CompletableFuture unexpected behaviour

Viewed 125

Here is the code, it runs as expected, no exception

fun main() {
    var mayBeEmptyString: String?

    mayBeEmptyString = "1";

    mayBeEmptyString?.let {        
        println("Inside let")
    } ?: run {
        throw RuntimeException("Inside run")
    }
}

Output:

Inside let

And here is the code that I am not able to understand how it works:

fun main() {
    var mayBeEmptyString: String?
    mayBeEmptyString = "1";
    mayBeEmptyString?.let {
//        println("Inside let")
        CompletableFuture.runAsync{ println("Inside let")}.join()
    } ?: run {
        throw RuntimeException("Inside run")
    }
}

Output:

Inside let  
Exception in thread "main" java.lang.RuntimeException: Inside run  
at com.test.TestKt.main(test.kt:15)  
at com.test.TestKt.main(test.kt)

Can anyone explain what is going on here? Thank you.

2 Answers

runAsync is meant for running a task that doesn't return a value, so you get a CompletableFuture<Void>, and attempting to read its value with get or join will give you null.

You then make this null result of join the result of your let block, which will cause your run block to be executed.

Because CompletableFuture.join() return null value cause

mayBeEmptyString?.let {
//        println("Inside let")
        CompletableFuture.runAsync{ println("Inside let")}.join()
    }

will be null and run { } will be executed

Related