https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Muhammad Talha

08/12/2022, 5:47 AM
Hi, I had a question about idiomatically returning a value from a callback function in Kotlin. In option A below I don’t need any qualified return and looks less “weird” to me. However, in other langs I usually see advocation of moving conditions “left”. So in B I’ve tried this. But now I need a qualified return in the condition. I have a feeling A is more idiomatic in Kotlin because we don’t need to unnecessarily add the qualified retun but this also goes against my desire to move as much “left” as possible 😅. Is there another way?
Copy code
// A)

validate { credential ->
    // ...
    if (/* ... */) {
        Some("thing")
    } else {
        null
    }
}

// B)

validate { credential ->
    // ...
    if (/* ... */) {
        return@validate Some("thing")
    }

    null
}
g

gaplotech

08/12/2022, 6:54 AM
You could use callable references to refactor your code to a cleaner way https://kotlinlang.org/docs/reflection.html#example-function-composition
Copy code
fun validate(fn: (Any) -> Any): Any {
    return fn(1)
}

validate { credential ->
    if(credential != 1) {
        return@validate true
    }
    false
}

// create a function
fun validateFn(credential: Any): Any {
    if(credential != 1) {
        return true
    }
    return false
}

// callable reference
validate(::validateFn)
j

Joffrey

08/12/2022, 8:12 AM
You don't have to use callable references, but at least extract the body of the lambda as functions when you can and this kind of problems is avoided altogether. This is usually more readable as well because you give a name to the code snippet so people immediately understand the purpose and can stay at a higher level when they read the calling function. A callable reference may or may not be more readable than a lambda containing one function call, though - that's for your own judgement.
m

Muhammad Talha

08/12/2022, 8:51 AM
I see! Yes this makes sense thank you. Easier to test as well.