bj0
02/14/2018, 8:12 PMcheck()
doesn't return a booleanRuckus
02/14/2018, 8:14 PMcheck
.bj0
02/14/2018, 8:17 PM= if(check(isConnected)) getNetworkResource()
or something like thatRuckus
02/14/2018, 8:48 PMcheck
by definition can't have an else. You could write your own guard
method though.
inline fun <T> guard(condition: Boolean, op: () -> T): T {
check(condition)
return op()
}
and then use = guard(isConnected) { getNetworkResource() }
bj0
02/14/2018, 9:04 PMcheck
that does the same thing but returns true
, I'm just saying the stdlib one would be more useful if it already did thatRuckus
02/14/2018, 9:07 PMIf you're using if as an expression rather than a statement (for example, returning its value or assigning it to a variable), the expression is required to have an else branch.
check
can never be reached, it doesn't make sense to use it as an expression. In your example of using it in an expression function, you don't have an else
block, which is required. So to fit that requirement, what would you put in the else block (keeping in mind it cannot be reached anyway)?bj0
02/14/2018, 9:16 PMif (!isConnected)
throw IllegalStateException("not connected.")
else
link.send(packet)
I just think it looks cleaner with check()
, and you could do other things like multiple, serial checksRuckus
02/14/2018, 9:23 PMcheck(isConnected) { "not connected" }
link.send(packet)
is more elegant and understandable than trying to cram the two distinct ideas into a single expression, though I may be the exception.