How do I use Mixins without inheritance?

dart, mixins

Solution

You have to inherit from another class if you want to use a mixin. However, you can simply inherit from Object:

class User extends Object with Persistence {
  // implementation
}

But really, you can just inherit from Persistence as well which will have the same effect:

class User extends Persistance {
  // implementation
}

Gilad Bracha explains that the syntax is specifically designed this way:

I think it is important to understand the semantic model here. "with" is the mixin application operator, and it takes two parameters: a superclass and a mixin, and yields a class. Saying "with Foo" in isolation makes as much sense as saying >> 2 (you could interpret both as curried functions, but that is very far from Dart). When you write "C extends S with M", you are specifying a superclass following the extends keyword, just as you do when you write "C extends K" except that the superclass is not specified via an identifier but via a mixin application. So the superclass would be "S with M".

As Lasse points out, as practical matter it doesn't restrict you, but having the syntax reflect the underlying structure is important.

Problem

Is it possible to apply a mixin to a class without the target class inheriting from any other class? For example, can I implement the following: ``` class User with Persistence { // implementation } ``` Most of your examples of Mixins in dart seem to be coupled with inheritance. Thanks in advance!

Original source

Related problems