Search code examples
typescriptdartrecursive-type

Recursive object types in Dart?


I should note that I'm coming from a TypeScript background which colors a lot of my perspective/nomenclature here.

In TypeScript you can define a recursive interface really easily:

interface User {
  name: string,
  friends: User[]
}

const bob:User = {
  name: "Bob",
  friends: []
}

How would you do this in Dart?


Solution

  • The solution is not much different.

    class User {
      String name;
      List<User> friends;
    }
    
    
    void main() {
      var bob = User();
      bob.name = "Bob";
      bob.friends = [User(), User(), User()];
    
      print(bob.name); // Bob
    
      print(bob.friends); // [Instance of 'User', Instance of 'User', Instance of 'User']
    }