Feature Request: Negate custom infix functions that return a Boolean


#1

When you wan’t to check if some object is an instance of a another class you can use this:
if(obj is String) doSomething()
And conveniently you can negate it using an exclamation mark instead of negating the complete statement:
!(obj is String) » obj !is String

But when I create my own infix fun I can’t do this. To achive a similar effect I have to do the following:

infix fun Player.has(rang: Rang): Boolean = rang.hasRang(this)
infix fun Player.hasNot(rang: Rang) = !(this has rang) // Workaround for !has

// Usecase example:
fun kick(player: Player, target: Player, reason: String): Boolean {
    if(player hasNot Rang.Admin) {
        player.sendMessage("You can't do this to ${target.name}.")
        return false // Unsuccessful
    }
    target.kick("You've been kicked by ${player.name} for the following reason:\n$reason")
    return true // Successful
}

So, in my opinion, it’s extremly neccessary to streamline the negation of infix functions to allow everybody to use them. I guess there shouldn’t be a problem for doing so, since the exclamation mark isn’t allowed in function-names anyway.


#2

https://youtrack.jetbrains.com/issue/KT-5351


#3

Thanks. Haven’t found that.

(This topic can get closed.)


#4

Boolean methods are usually used in if() expressions. It would be very handy to make boolean functions that have one parameter, to be infix by default. This way they would be more readable. Besides all boolean methods in java libraries could be used as infix functions.

Example:

if(java.util.Date().after(anotherDate)) ...

Would become:

if(java.util.Date() after anotherDate) ...

#5

This could be solved with user-level inline-only functions. (This exists in the standard library, but not at user level). Of course inline-only comes with various caveats that are probably the reason that it isn’t currently exposed.