Ballerina是否支持Switch-case?后续是否会新增该特性?
Hey there! Great question—let's clear this up for you:
Does Ballerina support switch-case?
Absolutely! Ballerina has a robust pattern-matching switch statement (fully rolled out in the Swan Lake release) that’s perfect for exactly your use case of returning different JSON responses based on a schoolId value. It’s way cleaner than chaining multiple if-else blocks.
Example: Replace your if-else with switch-case
Here’s how you can refactor your existing code to use a switch statement for your school ID scenario:
json schoolDetails = {}; switch schoolId { case "34534253" => { schoolDetails = { "schoolId": schoolId, "Name": "School ABC", "Address": "344 Scarbrough Ln, Cordova, TN 38018", "Principal": "John Due" }; } // Add more cases for other school IDs as needed case "98765432" => { schoolDetails = { "schoolId": schoolId, "Name": "School XYZ", "Address": "789 Oak Ave, Bartlett, TN 38133", "Principal": "Jane Smith" }; } default => { schoolDetails = { "schoolId": schoolId, "error": "Unknown school ID provided" }; } }
Why didn’t you find this in Ballerina-by-example?
It’s possible you might have missed the pattern matching section of the examples, since Ballerina’s switch is tightly integrated with its pattern-matching capabilities (it supports not just value matches, but type, structural, and even regex matches too!). If you were looking at older pre-Swan Lake documentation, those versions had limited or no switch support, but modern Ballerina (Swan Lake+) fully supports this feature.
Future of switch-case in Ballerina
The switch/pattern matching feature is a core part of Ballerina’s design, focused on making data-driven logic concise and readable. There are no plans to remove it—instead, the language team continues to expand pattern-matching capabilities in newer releases.
内容的提问来源于stack exchange,提问作者Lahiru Sandaruwan Gamage

