Hey, .. Is there neater way to do this ```fun foo...
# announcements
a
Hey, .. Is there neater way to do this
Copy code
fun foo() : Response {
             workFlowLog?.let {  Response.Sucess(BatchApprovalWorkFlowList(workFlowLog) ) } ?: run { Response.Error(Exception()) } 
}
My intention is to return different response in case workflow is null. My team mates say this kinda of ugly. Is there a better kotlin idiom to craft this statement. if( w == null) ... else ... , we are trying to avoid this.
e
can remove
run { }
, can't you?
a
yes i can however how do i return different kind of response in case workflow is null
e
either that,
if
, or
when
. go with whatever the team likes. nothing wrong with
if
if it's clearer
a
hm.. noted
r
fun foo() = workFlowLog?.let { Response.Sucess(BatchApprovalWorkFlowList(it) ) } ?: Response.Error(Exception())
a
@Rajkumar Singh i think you have misunderstood statement
r
@althaf can you ask your teammates what part is ugly? as ephemient said either
if
or
when
would also be fine.
d
Depending what the issue your team has with it, couldn’t you also have an extension function on nullable Response? Like orError that returns Response.Error(Exception()). No matter how you cut it you need to handle the not null case and the null case and the rest is just how it looks
💯 3
a
checkNotNull() i'm now thinking of using this one so a exception is raised an can be cleanly handled
@Dave K they say it looks ugly. 😄
😀 2
r
@althaf ask your teammate(s) to provide a non-ugly solution. I'm curious now.
☝️ 3
👀 2
d
Try/catch with the checkNotNull is one of a million other options
👀 1
e
you could make an extension function like
Copy code
inline fun <T : Any, R> T?.ifNotNull(orElse: () -> R = ::TODO, block: (T) -> R) = if (this == null) orElse() else block(this)
fun foo(): Response {
    workFlowLog.ifNotNull(orElse = { Response.Error(Exception()) }) { Response.Success(BatchApprovalWorkFlowList(it)) }
}
but that doesn't strike me as an improvement
👍 1