it's a shame `check()` doesn't return a boolean
# announcements
b
it's a shame
check()
doesn't return a boolean
r
What would it return? Assuming it returns, it's obviously true. If you just want to test if the statement, assign it to a variable, don't put it in
check
.
b
most likely return true, it would just make it easy to use in expressions if it returned true
like single expression functions
= if(check(isConnected)) getNetworkResource()
or something like that
r
That doesn't make a lot of sense to me, as an expression function would require an else and
check
by definition can't have an else. You could write your own
guard
method though.
Copy code
inline fun <T> guard(condition: Boolean, op: () -> T): T {
    check(condition)
    return op()
}
and then use
= guard(isConnected) { getNetworkResource() }
b
why would an expression require an else? And yea I could define my own
check
that does the same thing but returns
true
, I'm just saying the stdlib one would be more useful if it already did that
r
https://kotlinlang.org/docs/reference/control-flow.html#if-expression
If 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.
I know what you're saying, I'm just disagreeing. As the alternative to
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)?
b
yea I guess the compiler would have to be smart enough to figure that out. But it would be equivalent to
Copy code
if (!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 checks
r
Fair enough, but I think expression functions get a little abused in Kotlin. To me
Copy code
check(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.
2