# convertIfNecessary<T> method

T convertIfNecessary<T>(

1. String name,
2. Object pod, [
3. Class? type,
4. Class? source,

])

Converts a pod instance to the required type if necessary.

This method checks if the pod instance matches the required type and attempts to convert it using the conversion service if not.

`name` the name of the pod `pod` the pod instance to convert `type` the required type `source` the source type of the pod instance Returns the converted pod instance

Throws PodNotOfRequiredTypeException if conversion fails

## Implementation

    T convertIfNecessary<T>(String name, Object pod, [Class? type, Class? source]) {
      // Check if required type matches the type of the actual pod instance.
      Class? sourceType = source;
      if (source == null || !source.isInstance(pod)) {
        try {
          final cls = pod.getClass();
          if (cls.isInstance(pod)) {
            sourceType = cls;
          }
        } catch (ex) { }
      }

    		if (type != null && !type.isInstance(pod)) {
    			try {
    				final convertedPod = _conversionService.convertTo(pod, type, sourceType);
    				if (convertedPod == null) {
    					throw PodNotOfRequiredTypeException(name: name, requiredType: type, actualType: pod.getClass());
    				}

    				return convertedPod as T;
    			} on TypeError catch (ex) {
    				if (_logger.getIsTraceEnabled()) {
    					_logger.trace("Failed to convert pod '$name' to required type '${type.getSimpleName()}'", error: ex);
    				}

    				throw PodNotOfRequiredTypeException(name: name, requiredType: pod.getClass(), actualType: type);
    			}
    		}

    		return pod as T;
    }