How do I use Dart's new union types feature?
- User
How do I use Dart's new union types feature?
Assistant
Let me help explain Dart's union types feature, which was introduced in Dart 3.0.
Here's a basic example of how to use union types:
// Declare a union type using the '|' operator String | int id; // Can assign either type id = "abc123"; // Valid id = 42; // Also valid // Using type checks if (id is String) { print(id.toUpperCase()); // String methods available } else if (id is int) { print(id * 2); // Integer operations available }Some key points about union types in Dart:
- You can combine multiple types using the
|operator - The types can be nullable by adding
? - They work well with pattern matching:
void processValue(int | String | bool value) { switch (value) { case int i: print('Got integer: $i'); case String s: print('Got string: $s'); case bool b: print('Got boolean: $b'); } }- You can combine multiple types using the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.