https://kotlinlang.org logo
Title
b

bj0

02/14/2018, 8:12 PM
it's a shame
check()
doesn't return a boolean
r

Ruckus

02/14/2018, 8:14 PM
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

bj0

02/14/2018, 8:17 PM
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

Ruckus

02/14/2018, 8:48 PM
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.
inline fun <T> guard(condition: Boolean, op: () -> T): T {
    check(condition)
    return op()
}
and then use
= guard(isConnected) { getNetworkResource() }
b

bj0

02/14/2018, 9:04 PM
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

Ruckus

02/14/2018, 9:07 PM
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

bj0

02/14/2018, 9:16 PM
yea I guess the compiler would have to be smart enough to figure that out. But it would be equivalent to
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

Ruckus

02/14/2018, 9:23 PM
Fair enough, but I think expression functions get a little abused in Kotlin. To me
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