Created
September 30, 2021 12:51
-
-
Save lesnitsky/1e30966c49603513e75c528cc71d05cf to your computer and use it in GitHub Desktop.
runtimeType key
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
class Storage<T> { | |
final _internal = <Type, T>{}; | |
void add(T value, [Type? type]) { | |
_internal[type ?? T] = value; | |
} | |
T get<T>() { | |
return _internal[T] as T; | |
} | |
} | |
class Boxed<T> {} | |
class Container { | |
final storage = Storage<Boxed>(); | |
add(Boxed value) { | |
storage.add(value, value.runtimeType); | |
// ^^^^^^^^^^^^^^^^^^ | |
// can't use generic | |
} | |
Boxed<T> get<T>() { | |
return storage.get<Boxed<T>>(); | |
} | |
} | |
final container = Container(); | |
void main() { | |
final intValue = Boxed<int>(); | |
final stringValue = Boxed<String>(); | |
final doubleValue = Boxed<double>(); | |
final items = [intValue, stringValue, doubleValue]; | |
items.forEach((element) { | |
container.add(element); | |
}); | |
assert(container.get<int>() == intValue); | |
assert(container.get<String>() == stringValue); | |
assert(container.get<double>() == doubleValue); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment