On Sunday, 14 April 2013 at 23:54:57 UTC, bearophile wrote:
Idan Arye:

(because it's a useful function)

I think you should explain why you think it's useful.

Bye,
bearophile

Well, `predSwitch` has two main advantages on regular `switch`. The first is being able to choose your own predicate. `switch` is preferable to a chain of `if`-`else if` because it's a clearer syntax(and because of the usage of lookup tables, but `predSwitch` does not have that), but not all `if`-`else if` chains are about simple equality checking - sometimes you need to check for other things, like which collection contains a value. Choosing your own predicate is helpful for that.

The second advantage - which I consider much more important - it that `predSwitch` returns a value. This means you can use it mid-expression - for example, to initialize a constant, or to determine a function argument. You can't do those things with `switch` because it's a statement. If you try to initialize a constant in a `switch` statement, the constant's scope will be limited to the `case` where it is defined, and if you want to use `switch` to determine a function argument, you're gonna have to write the rest of the function call in each `case`.

Reply via email to