Single expression syntax is discouraged on `Unit` ...
# getting-started
f
Single expression syntax is discouraged on
Unit
functions, right?
Including main
l
Just for readability imho 🙂
s
Coding convenions only says:
Prefer using an expression body for functions with the body consisting of a single expression.
I cant really come up with an example of a Unit function that is only one line
a
You can still have return type with expression body though. e.g. you can do
fun massage(thing: Thing): Unit = thing.massage()
to highlight that it's a Unit function
f
I thought a single expression body on a
Unit
function is a bit misleading
l
It is in my opinion, you can do it, the language allow you to do so
But it’s not clear 🙂
s
Why is it misleading ?
f
Because the
=
seems to imply a meaningful value in my eyes
👍 2
l
Same 🙂
You stole my words haha
f
haha
I'm not very experienced though
l
I chose readability over code length
Using 2 graphs are not a problem if it help while reading code
s
Sure but that is extremely subjective territory. Larger code is objectively worse for readability in itself. There is nothing special about passing
Unit
down to the caller just like any other value.
l
Yep, we know that, we just said we don’t like using it that way, we didn’t say it’s wrong, it’s personal 🙂
f
Yeah I found a Reddit thread about that and the opinions there are very mixed as well
Some say it feels misleading, some say there's nothing wrong
Do you sometimes put the explicit type declaration on single expression functions?
Or are the IDE tools enough to figure it out on the fly
s
For public functions I always keep them explicit. Otherwise its too easy to change them by accident. For the rest I guess it depends on how far you want the inference to ripple.
There is an Intention to introduce an explicit type. Type hints may reveal them also but I dont use it
f
Are single expression functions discouraged when the expression is very big?
s
We use it sometimes to cut down on indentation. ie.
Copy code
fun dbAccess() = transaction {

}
As opposed to:
Copy code
fun dbAccess() : Result {
    return transaction {
        doSoemthing()
    }
}