Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Dart "sound null-safety" different from Kotlin null safety?

This Dart official video states that Dart's so-called "sound null safety" is better than Kotlin's null safety design, because it can optimise the code based on whether a variable is declared nullable, and other languages (I assume this refers to languages including Kotlin) have to do runtime checks to ensure null safety.

So, what extra optimisation does Dart do?

How does it interoperate with legacy codebases that null-safety is not supported while ensuring null safety?

like image 279
Yihao Gao Avatar asked Dec 03 '20 08:12

Yihao Gao


People also ask

What is Dart sound null safety?

Dart's null safety is sound, which enables compiler optimizations. If the type system determines that something isn't null, then that thing can never be null.

What is null safety in Kotlin?

Kotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws NullPointerException immediately if it found any null argument is passed without executing any other statements. Kotlin's type system is aimed to eliminate NullPointerException form the code.

When did Dart add null safety?

Dart introduced null safety in 2.12. 0, but there are old Dart codes in production. Since the Dart team can't migrate your code automatically.

How does null safety work in Flutter?

Null safety means that a variable cannot have a null or void value. This feature improves user satisfaction by reducing errors and app crashes. Null safety ensures that all runtime null-dereference problems are shown at compile-time.


Video Answer


1 Answers

So, what extra optimization does Dart do?

The most basic kind of optimization is that when performing calculations on numeric types, compiler can treat them (internally) as primitive types of non-reference types (unboxed values).

Why is that?

Because they cannot be null and, therefore, it is not necessary to use them as data of referenced types (boxed values).

Why is that?

Because null is represented in Dart as a null constant reference.
If there is no need to refer to this constant, then why not use value types instead of reference type? At least in the generated code, which can be optimized already at compile time.

All this thanks to the so-called "strong mode".
The strong mode in conjunction with non-nullable types allows you to optimize the code already at the compilation stage, which is very important for modes such as AOT, which do not allow code to be optimized at runtime, because it is in the RE (read and execute) mode.

How does it interoperate with legacy codebases that null-safety is not supported while ensuring null safety?

It seems to me that you should ask this as a separate question.

like image 175
mezoni Avatar answered Sep 20 '22 13:09

mezoni