Functional Boolean Expressions in Kotlin

If we have optionals why we cannot handle booleans using the similar approach?

test.kt
fun Boolean.ifTrue(then: () -> Unit): Boolean { 
    if (this) { 
        then.invoke() 
    } 
    return this; 
} 
 
fun Boolean.ifFalse(then: () -> Unit): Boolean { 
    if (!this) { 
        then.invoke() 
    } 
    return this; 
} 
 
fun main(args: Array<String>) { 
    (true).ifTrue { 
        // true 
    }.ifFalse { 
        // false 
    } 
}
or with infix

test.kt
infix fun Boolean.ifTrue(then: () -> Unit): Boolean { 
    if (this) { 
        then.invoke() 
    } 
    return this; 
} 
 
infix fun Boolean.ifFalse(then: () -> Unit): Boolean { 
    if (!this) { 
        then.invoke() 
    } 
    return this; 
} 
 
fun main(args: Array<String>) { 
    (true) ifTrue { 
        // true 
    } ifFalse { 
        // false 
    } 
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>