castCallbackResult<R> static method
ENG-011: Safely cast a callback result to the expected type R.
This handles the case where a generic method callback may return null
but the expected type R may or may not be nullable. For example,
SynchronousFuture.then<R>() where R could be String (non-nullable)
or String? (nullable).
Usage in generated bridge code:
return t.then((p0) {
final result = D4.callInterpreterCallback(visitor!, fn, [p0]);
return D4.castCallbackResult<R>(result);
});
Implementation
static R castCallbackResult<R>(Object? result) {
if (result == null) {
// Check if R accepts null (i.e., R is nullable like `String?`)
// The `null is R` test returns true for nullable types.
if (null is R) {
return null as R;
}
throw ArgumentD4rtException(
'Callback returned null but expected non-nullable type',
);
}
// Attempt to cast to R - explicit cast needed for AOT
if (result is R) {
return result as R;
}
// If direct cast fails, try unwrapping bridge values
final unwrapped = unwrapInterpreterValue(result);
if (unwrapped is R) {
// ignore: unnecessary_cast
return unwrapped as R; // Explicit cast for AOT
}
throw ArgumentD4rtException(
'Callback returned ${result.runtimeType}, expected $R',
);
}