You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 infers value as type T (in your example, int), since the action parameter is explicitly constrained to accept a T. No more dynamic type ambiguity.
  • Compile-Time Safety: Invalid callbacks like () => 42 (which don't accept a T parameter) will throw a compile error immediately, stopping runtime crashes before they happen.
  • Correct Recursion: We pass the action function itself to the child's visit method, 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) to child?.visit(), but action(value) returns void (for print-style actions). The visit method expects a function parameter, not a void value—this caused the runtime or compile error.
  • Scheme 3: You declared a generic T for the visit method itself, which shadowed the class's generic T. This broke type matching between the node's type and the callback's parameter type, leading to assignment errors.

内容的提问来源于stack exchange,提问作者Suragch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:17:41