I have a rudimentary question. ```fun foo() { ...
# getting-started
l
I have a rudimentary question.
Copy code
fun foo() {
    getData()?.let { data ->
        doSomething(data)
    }
}
Is it equivalent to this?
Copy code
fun foo() {
    val data = getData() ?: return
    doSomething(data)
}
I don't like adding more indentations, so came up with the second one. Is it OK?
d
Yes it does the same.
l
Thank you. I've never used like this, so it looked awkward a bit.
d
I also like this notation
Copy code
val data = getData()
if (data != null) doSomething(data)
I recommend having braces for if statements always unless it's a one liner. Never do this, it is error prone (in my opinion and experience):
Copy code
if (data != null)
    doSomething(data)
a
You could have also done
Copy code
fun foo() {
    getData()?.let(::doSomething)
}
l
Thank you guys. I'll give it a try if
return
is not needed.
In addition to the previous question, I wonder if this is a bad habit.
Copy code
fun foo() {
    bar() ?: return
    doSomething1()
    ...
}

fun bar(): Unit? {
    try {
        doSomething2()
    }
    catch (e: SomeException) {
        return null
    }
    ...
    return Unit
}
So I can handle functions in the same way whether or not they return a value. But I'm not sure if it's fine.
d
Explicitly returning Unit from Kotlin code seems like it's asking for trouble. This basically re-creates the "check the return value!" issue that the C stdlib has.
r
@lenqnr Why not just return a
Boolean
?
Then you can do
if (!bar()) return
d
Yeah I wouldn't recommend using
Unit?
. I wonder if you can omit the last return statement
l
Maybe I loved syntactic sugar too much. But
try... catch
in every functions feels a little verbose.
@Dico I can't omit it, but I can in
withContext
block. I don't know why.
d
What