coerce static method
dynamic
coerce(
- dynamic instance,
- ClassMirror targetClass, {
- dynamic coerce(
- dynamic o,
- ClassMirror tClass
Coerces the given object to the specified class (targetClass
).
*
-
coerce
- used to coerce the given object to the given type.
- If omitted or null is returned, the default coercion will be done (it
- handles the basic types:
int
,double
,String
,num
, andDatetime
). - It throws CoercionError if failed to coerce.
Implementation
static coerce(instance, ClassMirror targetClass,
{coerce(o, ClassMirror tClass)?}) {
if (coerce != null) {
final o = coerce(instance, targetClass);
if (o != null)
return o;
}
if (instance == null)
return instance;
final clz = reflect(instance).type;
if (isAssignableFrom(targetClass, clz))
return instance;
var sval = instance.toString();
if (targetClass == Mirror.String)
return sval;
if (sval.isEmpty)
return null;
if (targetClass == Mirror.int)
return int.parse(sval);
if (targetClass == Mirror.double)
return double.parse(sval);
if (targetClass == Mirror.num)
return sval.contains('.') ? double.parse(sval): int.parse(sval);
if (targetClass == Mirror.DateTime)
return DateTime.parse(sval);
if (targetClass == Mirror.bool)
return !sval.isEmpty && (sval = sval.toLowerCase()) != "false" && sval != "no"
&& sval != "off" && sval != "none";
throw CoercionError(instance, targetClass);
}