Skip to content

Instantly share code, notes, and snippets.

@fuzz6001
Last active April 22, 2024 00:45
Show Gist options
  • Save fuzz6001/705a9d566d7d79dcffda319aad9270be to your computer and use it in GitHub Desktop.
Save fuzz6001/705a9d566d7d79dcffda319aad9270be to your computer and use it in GitHub Desktop.
型情報を持つenum
/// [set]で自分と同じ型しか受け付けないようにしたい.
enum Test {
i(int),
d(double),
s(String),
;
final Type type;
const Test(this.type);
set(dynamic value) {
print(
'set $name = $value ($type vs ${value.runtimeType} => ${type == value.runtimeType})');
}
}
void main() {
final i = Test.i;
final d = Test.d;
final s = Test.s;
i.set(1);
i.set(3.14);
i.set('hoge');
i.set(100);
i.set(100.0);
print('');
d.set(1);
d.set(3.14);
d.set('hoge');
d.set(100);
d.set(100.0);
print('');
s.set(1);
s.set(3.14);
s.set('hoge');
s.set(100);
s.set(100.0);
print('');
}
@fuzz6001
Copy link
Author

fuzz6001 commented Apr 19, 2024

https://dartpad.dev/?id=705a9d566d7d79dcffda319aad9270be

小数部が 0 な double が int として扱われてしまう...。
String は問題なし。

set i = 1 (int vs int => true)
set i = 3.14 (int vs double => false)
set i = hoge (int vs String => false)
set i = 100 (int vs int => true)
set i = 100 (int vs int => true) // 受け付けたくない.

set d = 1 (double vs int => false)
set d = 3.14 (double vs double => true)
set d = hoge (double vs String => false)
set d = 100 (double vs int => false)
set d = 100 (double vs int => false) // 受け付けて欲しい.

set s = 1 (String vs int => false)
set s = 3.14 (String vs double => false)
set s = hoge (String vs String => true)
set s = 100 (String vs int => false)
set s = 100 (String vs int => false)

@fuzz6001
Copy link
Author

Dart の問題なのでどうしようもないか。

print(1.0.runtimeType); //=> int
print(1.1.runtimeType); //=> double

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment