getConverter<T> method

Converter<T>? getConverter<T>(
  1. RuntimeType<T> type,
  2. {bool logWarn = true}
)

Gets a Converter for a specific type.

If no converter has been registered for that type, nyxx_commands will try to find existing converters that can also convert that type. For example, a Converter<String> would be able to convert to Objects. Converters created like this are known as assembled converters and will log a warning when used by default.

You might also be interested in:

Implementation

Converter<T>? getConverter<T>(RuntimeType<T> type, {bool logWarn = true}) {
  if (_converters.containsKey(type)) {
    return _converters[type]! as Converter<T>;
  }

  List<Converter<T>> assignable = [];
  List<Converter<dynamic>> superTypes = [];

  for (final key in _converters.keys) {
    if (key.isSubtypeOf(type)) {
      assignable.add(_converters[key]! as Converter<T>);
    } else if (key.isSupertypeOf(type)) {
      superTypes.add(_converters[key]!);
    }
  }

  for (final converter in superTypes) {
    // Converters for types that superclass the target type might return an instance of the
    // target type.
    assignable.add(CombineConverter(converter, (superInstance, context) {
      if (superInstance.isOfType(type)) {
        return superInstance as T;
      }

      return null;
    }));
  }

  if (assignable.isNotEmpty) {
    if (logWarn) {
      logger.warning(
        'Using assembled converter for type ${type.internalType}. If this is intentional, you '
        'should register a custom converter for that type using '
        '`addConverter(getConverter(RuntimeType<${type.internalType}>(), logWarn: false))`',
      );
    }
    return FallbackConverter(assignable);
  }
  return null;
}