Sobes.tech
Junior — Middle

Объясните отличия между ключевыми словами final, const и var в контексте программирования.

sobes.tech AI

Answer from AI

In the Dart language (used in Flutter), the keywords final, const, and var have different meanings:

  • var — declares a variable with an implicit type, which can be changed after initialization.

  • final — declares a variable that can only be initialized once. After assignment, its value cannot be changed, but if it is an object, its internal state can be modified.

  • const — declares a compile-time constant. Its value must be known at compile time and cannot be changed at all. Such objects are immutable.

Example:

var a = 5;
 a = 10; // allowed

final b = 20;
// b = 30; // error, cannot change

const c = 100;
// c = 200; // error, cannot change

final list = [1, 2, 3];
list.add(4); // allowed, list content can be modified

const list2 = [1, 2, 3];
// list2.add(4); // error, const objects are immutable
Объясните отличия между ключевыми словами final… - sobes.tech