0

I'm new to Dart, and I'm trying to understand the 'as' operator. Initially, I thought it worked like the 'typecast' operator in C, but I'm realizing this may not be the case. Can someone explain the differences and similarities between these two operators?

When I run my code:

double x = 10.25, y = 2.3;
int result = (x / y) as int;
print(result);

I receive an error message that reads:

Unhandled exception:
type 'double' is not a subtype of type 'int' in type cast
#0      main (file:///C:/Users/UserName/Documents/VSCode/Dart/Lesson_18/Project_1/bin/main.dart:3:24)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#2      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)

I'm familiar with Dart's integer division operator, but I'm unclear on the purpose and behavior of the 'as' operator.

Siavash TS
  • 41
  • 4
  • 2
    Adding to the answer, if you want to do what you are trying to do, you can use: `int result = (x / y).toInt();` but even better, use `int result = x ~/ y;`. You can read about the `~/` operator here: https://api.dart.dev/stable/3.0.0/dart-core/num/operator_truncate_divide.html – julemand101 May 06 '23 at 09:33

1 Answers1

3

as is a cast, but also an assertion. You're saying "this value definitely is actually this other type, so let's call it that." This is different from a typecast in C where you're telling the compiler to trust you, and maybe even converting types between two completely different categories.

See also this discussion and the docs.

Zac Anger
  • 6,983
  • 2
  • 15
  • 42