Generic functions signature

PDF, Chapter 8: Generics, Paragraph Creating Generic FunctionsImplementing the Function:

Node<E>? createTree<E>(…) { … }

Can’t figure out where does the <E> in the function name createTree<E> come from? I didn’t see that signature in the previous chapters and the previous book — we always use just the functionName() syntaxis without angle brackets after the function name.

Can you explain it a little bit?

When you make a generic class, you add the name of the generic type after the class name. For example, in the following class definition:

class Node<T> {
  // ...
}

Writing <T> after the class name (that is, Node<T>) tells Dart that this class uses generics and the name of the generic type is T. If you delete <T> you’ll get errors anywhere you refer to T from within your class.

That’s how it is with a class. It’s also the same with a function. In the following example:

Node<E>? createTree<E>(…) {
  // ...
}

Writing <E> after the function name (that is, createTree<E>) tells Dart that this function uses generics and the name of the generic type is E. If you delete <E> you’ll get errors anywhere you refer to E from within your function.

Does that make sense?

Thanks for pointing this missing explanation out. It’s definitely worth explaining and I’ll create a TODO issue in the book repo to add something to the next edition.

2 Likes

Definitely. Thank you for detailed explanation!

1 Like