Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a oneline function calling a nullable variable function

Tags:

kotlin

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.

like image 725
Daniel Gomez Rico Avatar asked Dec 18 '22 19:12

Daniel Gomez Rico


2 Answers

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()
like image 120
7 revs, 2 users 98% Avatar answered May 23 '23 06:05

7 revs, 2 users 98%


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.

like image 41
mfulton26 Avatar answered May 23 '23 06:05

mfulton26