DEV Community

Alex Verein
Alex Verein

Posted on

Comparing switch-like operators in 14 different programming languages

We are going to look at Javascript, Typescript, Java, C#, Swift, Objective-C, Python, PHP, Ruby, Kotlin, ReasonML, Dart, Go and Elixir.

At Avo (avo.app) we work with 12 languages, and I decided to do a series of quick comparisons of those languages, plus 3 languages we are going to support soon.

First feature we are going to look at is the switch-like constructs. We are interested in 3 features related to switches - ability to use switch as an expression (so it returns a value), whether the switch construct is exhaustive (you need to handle all cases to compile the code) and if the fall-through logic disabled (so you don't need to break out of each case explicitly).

Language has switch expression is exhaustive no need to break reference
javascript limited, only if wrapped in a function https://stackoverflow.com/a/55944296 - - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
typescript limited, only if wrapped in a function limited http://ideasintosoftware.com/exhaustive-switch-in-typescript/ - same as JS
java starting java 12 expression is, statement is not additional syntax starting java 12 https://openjdk.java.net/jeps/354
c# starting C# 8.0 - (expression will give a compile warning) need to break in the statement https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
swift - + + https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
objc - + - 🤷‍♂️
python no switch in python :)
php called match, introduced in php 8 match is, switch is not match , switch is not https://www.php.net/manual/en/control-structures.match.php
ruby, called case + - + https://ruby-doc.org/core-3.0.1/doc/syntax/control_expressions_rdoc.html#label-case+Expression
kotlin, called when + expression is, statement is not + https://kotlinlang.org/docs/control-flow.html#when-expression
reasonml/rescript + + + https://rescript-lang.org/docs/manual/latest/pattern-matching-destructuring#switch-based-on-shape-of-data
dart - + - https://dart.dev/guides/language/language-tour#switch-and-case
go - - + https://tour.golang.org/flowcontrol/9
elixir (called case) - - (runtime error CaseClauseError) + https://elixir-lang.org/getting-started/case-cond-and-if.html#case

Top comments (0)