coerceMap<K, V> static method

Map<K, V> coerceMap<K, V>(
  1. Object? arg,
  2. String paramName, [
  3. InterpreterVisitor? visitor
])

Coerce a Map from D4rt to a typed Map.

D4rt creates Map<Object?, Object?> when evaluating map literals. This function coerces the map to the expected key and value types.

If visitor is provided and the value type V is a function type, InterpretedFunction values will be wrapped in proper callbacks.

Implementation

static Map<K, V> coerceMap<K, V>(
  Object? arg,
  String paramName, [
  InterpreterVisitor? visitor,
]) {
  if (arg == null) {
    throw ArgumentD4rtException(
      'Invalid parameter "$paramName": expected Map<$K, $V>, got null',
    );
  }

  // Handle BridgedInstance wrapping
  final value = arg is BridgedInstance ? arg.nativeObject : arg;

  if (value is! Map) {
    throw ArgumentD4rtException(
      'Invalid parameter "$paramName": expected Map<$K, $V>, got ${value.runtimeType}',
    );
  }

  // If already the correct type, return as-is
  if (value is Map<K, V>) {
    return value;
  }

  // Coerce each key-value pair to the expected types
  try {
    return value.map<K, V>((k, v) {
      final key = _coerceMapKey<K>(k, paramName, visitor);
      final val = _coerceMapValue<V>(v, paramName, visitor);
      return MapEntry(key, val);
    });
  } catch (e) {
    throw ArgumentD4rtException(
      'Invalid parameter "$paramName": cannot convert Map to Map<$K, $V> - $e',
    );
  }
}