Skip to content

Instantly share code, notes, and snippets.

@junddao
Last active June 9, 2023 02:14
Show Gist options
  • Save junddao/1f6bf772c67af84b2891e7ed4bff14a8 to your computer and use it in GitHub Desktop.
Save junddao/1f6bf772c67af84b2891e7ed4bff14a8 to your computer and use it in GitHub Desktop.
dart 3.0 _ pattern matching

dart 3.0 _ pattern matching

Created with <3 with dartpad.dev.

// pattern matching
void main() {
//validation
final user = ('miro', 30);
// build time 이 아닌 runtime에서 error 나게 할수 있음
final (name as String, age as int) = user;
// final (name as int, age as int) = user;
print(name);
print(age);
print('----------------');
switcher(['1', '2']);
switcher([1, 2]);
switcher([1, 2, 3]);
switcher(['1', '2', '3']);
switcher([1, '2']);
print('----------------');
print(switcher2(5, true));
print(switcher2(7, true));
print(switcher2(7, false));
print('----------------');
ifMatcher();
}
void switcher(dynamic gg){
switch(gg){
case 'aa':
print('match aa');
case ['1', '2']:
print('match [1, 2]');
// 3개가 들어간 어떤 list 도 다 잡아
case [_, _, _]:
print('match [_, _, _]');
case [int a, int b]:
print('match [int $a, int $b]');
// 조건도가능
// case <10 && > 5:
// print('match <10 && > 5 ');
default:
print('no match');
}
}
String switcher2(dynamic val, bool condition) => switch(val){
5 => 'match 5',
7 when condition => 'match 7 and true',
_ => 'no match',
};
void ifMatcher(){
final user ={
'name': 'miro',
'age' : 10,
};
if(user case {'name': String name, 'age': int age}){
print(name);
print(age);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment