Switch statements with string values

Sunday, February 14, 2010
I decided to go ahead and implement string case values for switch statements:

def setOption(key:String, value:String) {
  switch key {
    case "TargetLanguage" {
      targetLanguage = value;
    }

    case "TokenType" {
      tokenTypeName = value;
    }
      
    case "TokenPrefix" {
      tokenNamePrefix = value;
    }
      
    case "StateType" {
      stateTypeName = value;
    }

    case "StartState" {
      startStateName = value;
    }

    else {
      // log unknown option
    }
  }
}

Currently it just transforms this construct into a sequence of if/else statements. However, it would be possible to optimize this by precomputing a hash value for each string, or making a first-letter index table.

In fact, it wouldn't be hard to extend this to any data type that is (a) hashable, and (b) representable as a constant literal. However, I'm not sure I want to go that far.

0 comments:

Post a Comment