castElementCheck method

Object? Function(Object?)? castElementCheck(
  1. List<RuntimeType>? typeArguments, [
  2. int index = 0
])

The element check of cast<T>() for the stdlib bridges (ghissues30): the function a cast view runs on each element read through it or written into it, answering the element or throwing the TypeError Dart raises. index picks the type argument (Map.cast<K, V> has two).

Null when nothing can fail the check: no type argument, a top type, or a type the interpreter cannot judge (a type parameter, a function or record type) - the view then stays the lenient cast<dynamic>().

Implementation

Object? Function(Object?)? castElementCheck(
  List<RuntimeType>? typeArguments, [
  int index = 0,
]) {
  if (typeArguments == null || typeArguments.length <= index) return null;
  final type = typeArguments[index];
  if (!_castChecks(type)) return null;
  return (element) {
    if (_castAccepts(element, type)) return element;
    final valueType = element is InterpretedInstance
        ? element.klass.name
        : element is BridgedInstance
        ? element.bridgedClass.name
        : element.runtimeType.toString();
    throw D4rtTypeError(
      "type '$valueType' is not a subtype of type '${type.name}' in type "
      'cast',
    );
  };
}