Hi. Can anyone explain me what the difference is b...
# coroutines
m
Hi. Can anyone explain me what the difference is between below two functions?
Copy code
fun main(): Unit = runBlocking {
    launch {
        //CASE 1 : Will make the application main thread crash
        val result = returnAsKotlinResultFunc()

        //CASE 2 : Will not make the application main thread crash
//        val result = returnAsValueFunc()

        println("Return value : $result")
    }.join()
}

suspend fun returnAsKotlinResultFunc(): Result<String> = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    val result = runCatching {
        delay(100)
        throw IllegalStateException()
    }
    result
}


suspend fun returnAsValueFunc(): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    val result = runCatching {
        delay(100)
        throw IllegalStateException()
    }
    "Result : $result"
}
returnAsKotlinResultFunc
makes the application crash. seems like It can't catch the exception. On the other hand,
returnAsValueFunc
can normally handle the exception and return the String result. I think the return type is the only different thing they have. Have I missed something on it? (I am using below compiler options to return Result type.
Copy code
kotlinOptions {
    freeCompilerArgs = [
            "-Xallow-result-return-type",
            //"-Xexplicit-api=strict"
    ]
}
v
Your code is workable on IntelliJ using the following options:
Copy code
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
    }
}
m
@Val Salamakha Thank you for the comment. :) and my question is why 'returnAsKotlinResultFunc' makes app crashed even though it catchs the exception.
v
Read the following: https://stackoverflow.com/questions/52631827/why-cant-kotlin-result-be-used-as-a-return-type The rationale behind these limitations is that future versions of Kotlin may expand and/or change semantics of functions that return Result type and null-safety operators may change their semantics when used on values of Result type. In order to avoid breaking existing code in the future releases of Kotin and leave door open for those changes, the corresponding uses produce an error now. Exceptions to this rule are made for carefully-reviewed declarations in the standard library that are part of the Result type API itself.
m
@Val Salamakha Thank you again! I have already read the limitation and I thought this strange behavior has nothing to do with the limitation. and I wanted to know the reason behind the scene. Anyway, thanks for taking your time. enjoy coding :)