Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an object's class included a mixin in Dart?

Tags:

mixins

dart

How do I check whether an object's class included a mixin? For example:

class AClass extends Object with MyMixin {}
class BClass extends Object              {}

classIncludesMixin(new AClass(), 'MyMixin'); // => true
classIncludesMixin(new BClass(), 'MyMixin'); // => false

What should be in this classIncludesMixin() method in order for it to work?

like image 481
snitko Avatar asked Jan 10 '14 09:01

snitko


People also ask

What is the difference between class and mixin in Dart?

A mixin is a class with methods and properties utilized by other classes in Dart. It is a way to reuse code and write code clean. Mixins, in other words, are regular classes from which we can grab methods (or variables) without having to extend them. To accomplish this, we use the with keyword.

Which keyword is used for the mixin to implement in a class in Dart?

Mixin is a different type of structure, which can only be used with the keyword with. In Dart, a class can play the role of mixin if the class is does not have a constructor.

What is a mixin in Dart?

A mixin is a class whose methods and properties can be used by other classes – without subclassing. It's a reusable chunk of code that can be “plugged in” to any class that needs this functionality. Mixins are supported by Dart, and Flutter uses them in many places.

How do you use the mixin class in flutter?

To implement a mixin , create a class that extends Object and declares no constructors. Unless you want your mixin to be usable as a regular class, use the mixin keyword instead of class . In this way, your Car can run , but cannot be ' handleControlled '.


1 Answers

You can simply use a type check o is MyMixin (that will be also true for inheritance and implementation).

If you really have to check the mixin clause you have to use dart:mirrors :

bool classIncludesMixin(o, String mixinName) {
  var c = reflect(o).type;
  while (c != null) {
    var m = c.mixin;
    if (c != m && m.simpleName == new Symbol(mixinName)) return true;
    c = c.superclass;
  }
  return false;
}
like image 66
Alexandre Ardhuin Avatar answered Sep 27 '22 23:09

Alexandre Ardhuin