Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #206 Switch statement with strings

Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.

switch (str){
	case "bar":
            bar();
            break;
        case "baz":
            baz();
            break;
        case "foo":
            foo();
            break;
        case "barfl":
            barfl();
            break;
        default:
            somethingElse();
    }

A break is required at the end of every case
switch (str) {
    case "foo" -> foo();
    case "bar" -> bar();
    case "baz" -> baz();
    case "barfl" -> barfl();
}

This syntax is from JDK 7, and above; referred to as a "switch expression".
(some-> str {"foo" foo "bar" bar "baz" baz "barfl" barfl} (.call))

map is a function of a key, which return value for that key, if any.

There is case, but unlike map {} it is opaque, and you can't see which functions are whitelisted in runtime.

.call is a java.util.concurrent.Callable/call

New implementation...
< >
tkoenig