as method

ResolvableType as(
  1. Type type
)

Returns this type as a ResolvableType of the specified target type.

This method attempts to view this ResolvableType as an instance of the specified target type. It checks inheritance hierarchies and interface implementations to determine if this type can be viewed as the target type.

Parameters:

  • type: The target Type to view this ResolvableType as

Returns:

  • ResolvableType representing this type as the target type
  • ResolvableType.NONE if this type cannot be viewed as the target type

Example:

final listType = ResolvableType.forClass(List<String>);
final stringType = ResolvableType.forClass(String);

final listAsIterable = listType.as(Iterable);
print(listAsIterable != ResolvableType.NONE); // true - List implements Iterable

final listAsObject = listType.as(Object);
print(listAsObject != ResolvableType.NONE); // true - List extends Object

final stringAsIterable = stringType.as(Iterable);
print(stringAsIterable == ResolvableType.NONE); // true - String is not Iterable

// Useful for type casting and validation
T? castIfPossible<T>(ResolvableType type, Object instance) {
  final asTargetType = type.as(T);
  if (asTargetType != ResolvableType.NONE && asTargetType.isInstance(instance)) {
    return instance as T;
  }
  return null;
}

Implementation

ResolvableType as(Type type) {
  if (this == NONE) return NONE;

  final resolved = resolve();
  if (resolved == null) return NONE;

  if (resolved.getType() == type) {
    return this;
  }

  // Check if this type is assignable to the target type
  final targetClass = Class.forType(type);
  if (targetClass.isAssignableFrom(resolved)) {
    return this; // Return current type, not new type for target
  }

  // Check interfaces
  for (final interfaceType in getInterfaces()) {
    final interfaceAsType = interfaceType.as(type);
    if (interfaceAsType != NONE) {
      return interfaceAsType;
    }
  }

  return getSuperType().as(type);
}