Hi everyone! If some 3rd party lib is providing t...
# getting-started
l
Hi everyone! If some 3rd party lib is providing the following couple of functions:
Copy code
fun find(session: Session, query: Query) {}
fun find(query: Query) {}
Is there a cleaner way than this to pick which one to use?
Copy code
fun caller(session: Session?) {
    val query = Query()
    if (session == null) {
        return find(query)
    }
    return find(session, query)
}
Thanks!
a
You can write your own
find
with a default
null
value for the
session
parameter, and call it from everywhere.
Copy code
fun myFind(query: Query, session: Session? = null) = if (session == null) find(query) else find(session, query)
l
Thanks a lot! That's definitely one way to go. Any "syntactic sugar" alternatives that wouldn't require my own
find
function?
a
You have to explicitly call one of the
find
functions, so whatever you write, it will at least have the two expressions
find(session, query)
and
find(query)
. Given that, how much shorter than
Copy code
if (session == null) find(query) else find(session, query)
can you go?
l
Thanks again! That clears it for me
t
return session?.let { find(it, query) } ?: find(query)
a
@Ties That’s a bad idea. If
find(it, query)
returns
null
, you will end up calling
find(query)
too.
t
Ah yes, didn't think of that (and adding another Elvis operator would not make it prettier)