Nikita 웃
Nikita 웃

Reputation: 2060

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?

Upvotes: 2

Views: 2880

Answers (2)

Bhanuchander Udhayakumar
Bhanuchander Udhayakumar

Reputation: 1621

For more information about your question,

  1. def a variable inside if or else not works outside (your question scenario)
  2. Making global def works everywhere (wkt).
  3. You can use a variable in global even without def them like below shown code.
    code:

without 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

Upvotes: 0

Nitin Dhomse
Nitin Dhomse

Reputation: 2612

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

Upvotes: 1

Related Questions