Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-7-sonnet-20250219· AnthropicHugging Face LMArena Human Preference 140K

dart语言中:支持对任意对象进行 switch,并可以使用 when 子句添加守卫条件。是啥意思?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with grok-3-preview-02-24’s answer.
  1. User

    dart语言中:支持对任意对象进行 switch,并可以使用 when 子句添加守卫条件。是啥意思?

  2. Claude Assistant

    在Dart语言中,switch语句的功能比较强大,它支持对任意对象进行模式匹配,而不仅限于整数、字符串等简单类型。

    "when子句添加守卫条件"的意思是,你可以在case分支中使用when关键字添加额外的条件判断,只有当这个条件为true时,才会执行该分支的代码。

    例如:

    void checkValue(dynamic value) {
      switch (value) {
        case int i when i > 0:
          print('正整数: $i');
        case int i when i < 0:
          print('负整数: $i');
        case int i:
          print('零: $i');
        case String s when s.length > 5:
          print('长字符串: $s');
        case String s:
          print('短字符串: $s');
        case List list when list.isNotEmpty:
          print('非空列表,长度: ${list.length}');
        default:
          print('其他类型: $value');
      }
    }
    

    这个例子展示了如何对不同类型的对象进行switch,并使用when子句添加额外的条件判断。这使得Dart的switch语句非常灵活和强大。

    需要我解释或者展示更多关于这个特性的例子吗?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.