Syed
Syed

Reputation: 16513

How can I make Generics work in Dart language?

I am totally new to Dart and class OOP, please help me understand the issue I have mentioned below in my comments in my code.

main() {
  var shape = new Slot<Circle>();
  shape.insert(new Circle());
}

class Circle {
  something() {
    print('Lorem Ipsum');
  }
}

class Square {}

class Slot<T> {
  insert(T shape) {
    print(shape); // Instance of 'Circle'
    print(shape.something()); // The method 'something' isn't defined for the class 'dart.core::Object'.
  }
}

My question is, how can I call method that's in the Instance of 'Circle' and why am I getting the error?

Upvotes: 1

Views: 340

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276951

You need to notify the compiler that your generic implements a specific interface:

abstract class DoSomething {
  void something();
}

class Shape<T extends DoSomething> {
  T value;

  foo() {
    // works fine
    value.something();
  }
}

Upvotes: 4

Related Questions