Optional boolean "only if true" expression


#1

Is there a YT ticket for anything like this language enhancement?
someOptBoolean? <=> someOptBoolean == true

thus if (someOptBoolean?) <=> if (someOptBoolean == true)
then if (!someOptBoolean?) <=> if (someOptBoolean != true), even though it looks weird, but meaning is clear, I think.

Or just auto-convert opt-boolean to boolean with meaning (opt-boolean == true), if boolean is required.

Would love to have that, thanks!


#2

I think this is what your looking for:
https://youtrack.jetbrains.com/issue/KT-5965

The way I like to deal with it is with two functions:

//if positive
inline fun < reified T> ifp(cond: Boolean?, statements: ()->T) : T{
    if(condition == true) return statements()
}

and

//if negative
inline fun <reified T> ifn(con: Boolean?, statements: ()->T): T{
    if(condition == false) return statements()
}

You can expend it to returning a class with methods to support:

ifp(someOptBoolean){
     ...
}.ElseIf (someOtherOptBoolean) {
    ...
} Else {
    ...
}

but if you want to use that and want to return something, you need to call endIf as well.


#3
someOptBoolean ?: true

I consider the explicit replacement is clearer.
In some contexts null means false.


#4

Thanks for those inlines, very cool.


#5

worked out the ifelse.
Is probably overkill, but for fun:

WARNING: In the ReturningIfContinuation, the generic is determained using the top level function.
In this way, there is no unsafe cast.
The drawback is that when you return multiple types, the compiler may infer a different type.

val t = retIfP(true){
    ""
} else {
    null  //expected type of String
}

to solve this:

val t = retIfP<String?>(true){
    ""
} else {
    null
}