Dart中为泛型Node类实现带泛型参数的类型安全Void回调visit方法
Solution for Type-Safe Recursive
visit Method in Dart's Generic Node Class Let's fix this step by step. The core issue in your initial attempts was a simple mistake in the recursive call—you were passing the result of action(value) instead of the action function itself. Here's the correct implementation:
class Node<T> { Node(this.value); T value; Node? child; void visit(void Function(T) action) { // Execute the action on the current node's value action(value); // Recursively pass the action function to the child node child?.visit(action); } @override String toString() => value.toString(); }
Why This Works
- Proper Type Inference: When you call
root.visit((value) => print(value)), Dart automatically infersvalueas typeT(in your example,int), since theactionparameter is explicitly constrained to accept aT. No moredynamictype ambiguity. - Compile-Time Safety: Invalid callbacks like
() => 42(which don't accept aTparameter) will throw a compile error immediately, stopping runtime crashes before they happen. - Correct Recursion: We pass the
actionfunction itself to the child'svisitmethod, not the result of executing it. This fixes the runtime/compile errors from your first two attempts.
Testing the Implementation
Your sample main function will now behave exactly as expected:
void main() { final root = Node(1); root.child = Node(2); root.child!.child = Node(3); root.visit(print); // Outputs 1, 2, 3 root.visit((value) => print(value)); // Also outputs 1, 2, 3 // The following line throws a compile error (as intended): // root.visit(() => 42); }
What Went Wrong in Your Attempts
- Schemes 1 & 2: You tried to pass
action(value)tochild?.visit(), butaction(value)returnsvoid(for print-style actions). Thevisitmethod expects a function parameter, not avoidvalue—this caused the runtime or compile error. - Scheme 3: You declared a generic
Tfor thevisitmethod itself, which shadowed the class's genericT. This broke type matching between the node's type and the callback's parameter type, leading to assignment errors.
内容的提问来源于stack exchange,提问作者Suragch
相关产品推荐
相关产品推荐

