CreativeMind CreativeMind - 9 months ago 96
Groovy Question

Groovy: Proper usage of if else

I have this groovy code which works fine by itself:

def msg = "$evt.displayName was locked7 ${userName ? "by " + userName + " " : ""}$lockMode" // Default message to send


When I put it inside this simple if else block, it doesn't work at all (neither the first condition nor the else condition do anything).

if (i == 999) { //For Schlage One touch lock function
def msg = "$evt.displayName was locked via One Touch" // Default message to send
} else {
def msg = "$evt.displayName was locked7 ${userName ? "by " + userName + " " : ""}$lockMode" // Default message to send
}


Is there something incorrect in my code?

Answer Source

If you have the single line statement after if or else condition you can use if..else statement without {}, for multiple statements you must need to use curly braces {}.

    def msg = ""
    int i = 999
    if (i == 999) 
       msg = "$evt.displayName was locked via One Touch" // Default message to send
    else 
       msg = "$evt.displayName was locked7 ${userName ? "by " + userName + " " : ""}$lockMode" // Default message to send

    println "MESSAGE: "+msg
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download