https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Luis

02/11/2022, 3:09 PM
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

Alexander Maryanovsky

02/11/2022, 3:11 PM
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

Luis

02/11/2022, 3:14 PM
Thanks a lot! That's definitely one way to go. Any "syntactic sugar" alternatives that wouldn't require my own
find
function?
a

Alexander Maryanovsky

02/11/2022, 3:16 PM
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

Luis

02/11/2022, 3:20 PM
Thanks again! That clears it for me
t

Ties

02/11/2022, 7:40 PM
return session?.let { find(it, query) } ?: find(query)
a

Alexander Maryanovsky

02/13/2022, 9:33 PM
@Ties That’s a bad idea. If
find(it, query)
returns
null
, you will end up calling
find(query)
too.
t

Ties

02/14/2022, 8:05 AM
Ah yes, didn't think of that (and adding another Elvis operator would not make it prettier)