Skip to content

Instantly share code, notes, and snippets.

@szepeshazi
Created June 7, 2017 08:01
Show Gist options
  • Save szepeshazi/ebcd1436c6c0c418736cf22a1b5c4af9 to your computer and use it in GitHub Desktop.
Save szepeshazi/ebcd1436c6c0c418736cf22a1b5c4af9 to your computer and use it in GitHub Desktop.
Dart generic methods
abstract class Bunny {
String name;
void attack();
}
class Fluffy extends Bunny {
void attack() {
print('Licks hands violently');
}
}
class BloodBunny extends Bunny {
void attack() {
print('Rips throat open');
}
}
T createBunny<T extends Bunny>(String name) {
Bunny bunny;
if (T is Fluffy) {
bunny = new Fluffy()
..name = name;
} else if (T is BloodBunny) {
bunny = new BloodBunny()
..name = name;
} else {
print('Fatal: Unexpected type T: ' + T.toString());
}
return bunny;
}
main() {
final bunny = createBunny<Fluffy>('Priscilla');
bunny.attack();
}
@szepeshazi
Copy link
Author

Will output:

Fatal: Unexpected type T: dynamic
Unhandled exception:
NoSuchMethodError: The method 'attack' was called on null.
Receiver: null
Tried calling: attack()
#0 Object._noSuchMethod (dart:core-patch/object_patch.dart:43)
#1 Object.noSuchMethod (dart:core-patch/object_patch.dart:47)
#2 main (file:///C:/Users/aszepeshazi/IdeaProjects/video-service-connector/bin/bunny.dart:35:9)
#3 _startIsolate. (dart:isolate-patch/isolate_patch.dart:265)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:151)

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