Switch in Groovy

Our example program demonstrates the use of switch statements. Here’s the full source code.

import java.time.DayOfWeek
import java.time.LocalTime

def i = 2
println "Write ${i} as "
switch (i) {
    case 1:
        println "one"
        break
    case 2:
        println "two"
        break
    case 3:
        println "three"
        break
}

def today = DayOfWeek.from(java.time.LocalDate.now())
switch (today) {
    case DayOfWeek.SATURDAY, DayOfWeek.SUNDAY:
        println "It's the weekend"
        break
    default:
        println "It's a weekday"
        break
}

def now = LocalTime.now()
switch (true) {
    case now.hour < 12:
        println "It's before noon"
        break
    default:
        println "It's after noon"
        break
}

def whatAmI = { obj ->
    switch (obj) {
        case Boolean:
            println "I'm a bool"
            break
        case Integer:
            println "I'm an int"
            break
        default:
            println "Don't know type ${obj.getClass().getSimpleName()}"
            break
    }
}

whatAmI(true)
whatAmI(1)
whatAmI("hey")

Here’s how you can run the Groovy script:

$ groovy SwitchExample.groovy
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String

Groovy scripts can be executed directly using the groovy command. Save the script in a file named SwitchExample.groovy and run the command shown above.

Now that we can run and build basic Groovy programs, let’s learn more about the language.