If I have something like:
fun showProgressView() = ultraRecyclerView?.showProgressBar()
it says that it returns Unit?
and not Unit
(edited)
-----EDIT-----
One way can be
fun showProgressView() = ultraRecyclerView?.showProgressBar() ?: Unit
but it looks not right for me.
Another way:
fun showProgressView() { ultraRecyclerView?.showProgressBar() }
But I cant find a way for android studio maintain that format.
If you use the short expression form of a function, the inferred result type of the expression determines the function return type. If that is a platform type from Java, it could be nullable. If it is a Kotlin type then it will know the correct nullability.
But since you use the safe operator ?.
you are saying for sure it could be nullable. And if the result is null
or Unit
then that gives the inferred result type of Unit?
Which is odd, but is exactly what you are saying. Therefore, either use a normal function body with { .. }
or give the function an explicit return type if possible.
fun showProgressView(): Unit { ultraRecyclerView?.showProgressBar() }
You can also erase the nullability, by creating an extension function on Unit?
:
fun Unit?.void() = Unit
And use it whenever you want to fix the return type:
fun showProgressView() = ultraRecyclerView?.showProgressBar().void()
IntelliJ IDEA / Android Studio do not appear to have a setting to keep the style of a block body function on a single line. Even so, you can use run
to get around this:
fun showProgressView() = run<Unit> { ultraRecyclerView?.showProgressBar() }
Normally you do not need to add explicit type arguments to run
but in this case providing them gives you the desired method signature (return type of Unit
and not Unit?
).
Note: This answer is adapted from a comment I gave to why assignments are not statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With