Last active
April 22, 2024 00:45
-
-
Save fuzz6001/705a9d566d7d79dcffda319aad9270be to your computer and use it in GitHub Desktop.
型情報を持つenum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// [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(''); | |
} |
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
https://dartpad.dev/?id=705a9d566d7d79dcffda319aad9270be
小数部が 0 な double が int として扱われてしまう...。
String は問題なし。