Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Rewriting of switch statement

In D every const buildin type is allowed in a switch statement. An object reference cannot be const, because const fields cannot be initialized in the static or instance ctor. In Java final fields can be instialized in the ctors or can use e.g. new in the field initializer. This means, D and Java do not have compatible switch statements.

Because of that, TioPort devides it in two parts.

  • calculation of a case number
  • switch on this case number.

E.g. Java code:

  final int a = somefunc();
  /// ....
  switch( getSwitchValue() ){
  case a:
    doCaseA();
    break;
  default:
    doDefault();
    break;
  }

result in this D code:

  int a;
  static this(){
    a = somefunc();
  }
  /// ....

  {
    int calc_switch_value_034( int aValue ){
      if( aValue == a ){
        return 0;
      }
      return 1;
    }
    switch( calc_switch_value_034( getSwitchValue() ){
    case 0:
      doCaseA();
      break;
    case 1:
      doDefault();
      break;
    }
  }

With that refactoring, switching is also possible with variable, that are not const in the sense of D.