Mis on Never tüüp Dart keeles?
sobes.tech AI
Vastus AI-lt
The Never type is an indicator that an expression will never successfully complete. It is used for functions and methods that either throw an exception or enter an infinite loop.
Examples of usage:
-
Function that throws an exception:
Never _throwError(String message) { // Throws an exception, the function never returns a value throw StateError(message); } -
Function with an infinite loop:
Never _infiniteLoop() { // Enters an infinite loop, the function never terminates while (true) { // Do something } }
The main advantage of Never is that it helps the compiler understand that code after such a function or method call is unreachable, allowing static analysis to detect potential errors such as unreachable code and incorrect error handling.
Unlike void, which indicates that a function does not return a value (but completes successfully), Never indicates that the function will never complete in principle.
// Function returning void (completes successfully, but without a value)
void doSomething() {
print('Doing something');
}
// Function returning Never (never successfully completes)
Never crashAndBurn() {
throw 'Oh no!';
}
The Never type is a bottom type, meaning it is a subtype of any other type. This allows using a function returning Never in places where any other type is expected.