var.visit

auto visit(handlers...)() const @safe

Apply a visitor pattern to this value, dispatching to the appropriate handler based on type.

This provides type-safe dispatch without manual switch on Type, similar to std.variant.visit. Handlers are provided as template arguments and can be lambdas, function pointers, or delegates.

Handler Selection:

  • Handlers accepting specific types (bool, long, double, string, var[], var[string]) are matched first.
  • A handler accepting var serves as a catch-all fallback.
  • If no matching handler is found for the current type, returns the default value of the return type.

Type Mapping:

  • NULL: matched by typeof(null) handler or fallback
  • BOOL: matched by bool handler
  • Integer types (BYTE..ULONG): matched by long handler (widened)
  • Floating types (FLOAT, DOUBLE, REAL): matched by double handler (widened)
  • STRING: matched by string handler
  • ARRAY: matched by var[] handler
  • OBJECT: matched by var[string] handler
  • Character types (CHAR, WCHAR, DCHAR): matched by dchar handler (widened)

Parameters

handlersOne or more callable handlers for different types.

Returns

The result of calling the matched handler, or R.init if no handler matches.

Examples

var v = 42;
string result = v.visit!(
  (long n) => "integer: " ~ n.to!string,
  (string s) => "string: " ~ s,
  (var fallback) => "other: " ~ fallback.toString()
);
assert(result == "integer: 42");

var s = "hello";
auto r = s.visit!(
  (long n) => n * 2,
  (string str) => cast(long)str.length
);
assert(r == 5); // length of "hello"