Sdk: kotlin 'when' conditional operator equivalent in dart

Created on 21 Jan 2019  路  2Comments  路  Source: dart-lang/sdk

Need a kotlin like 'when' conditional operator.

Need a optional break statement and when like concise syntax, because it is less boilerplate and like a modern language. And a when or switch expression statement.

area-language type-enhancement

Most helpful comment

The Kotlin when statement is similar to a switch statement, but with more powerful patterns:

when (e) {
  (computedExpression) -> /* equality test with non-constant value */
  99, 100, 101 -> /* multiple patterns */
  in 10..25 -> /*range pattern */
  !in 10..20 -> /* not in range */
  is String -> /* type match */
  !is String -> /* negative type match */
  x.isEven -> /* boolean test */
}

It has implicit break between cases (no fallthrough), and allows a variable declaration in the switch expression:

when (var x = something) {
  is String -> print(x) 
  else -> print("$x")
}

which is in scope in the rest of the when.

A when can occur as an expression, in which case it likely requires an else branch. The value of the when is the value of the last expression in the chosen branch.

All 2 comments

The Kotlin when statement is similar to a switch statement, but with more powerful patterns:

when (e) {
  (computedExpression) -> /* equality test with non-constant value */
  99, 100, 101 -> /* multiple patterns */
  in 10..25 -> /*range pattern */
  !in 10..20 -> /* not in range */
  is String -> /* type match */
  !is String -> /* negative type match */
  x.isEven -> /* boolean test */
}

It has implicit break between cases (no fallthrough), and allows a variable declaration in the switch expression:

when (var x = something) {
  is String -> print(x) 
  else -> print("$x")
}

which is in scope in the rest of the when.

A when can occur as an expression, in which case it likely requires an else branch. The value of the when is the value of the last expression in the chosen branch.

It would also be great to make the result of the when clause assignable to a variable, return, etc.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Hixie picture Hixie  路  3Comments

bergwerf picture bergwerf  路  3Comments

rinick picture rinick  路  3Comments

jmesserly picture jmesserly  路  3Comments

xster picture xster  路  3Comments