Programing

Dart에서 "const"와 "final"키워드의 차이점은 무엇입니까?

crosscheck 2020. 10. 8. 07:41
반응형

Dart에서 "const"와 "final"키워드의 차이점은 무엇입니까?


Dart에서 constfinal키워드 의 차이점은 무엇입니까 ?


dart의 웹 사이트에 게시물이 있으며 꽤 잘 설명되어 있습니다.

결정적인:

"final"은 단일 할당을 의미합니다. 최종 변수 또는 필드 에는 이니셜 라이저가 있어야합니다 . 값이 할당되면 최종 변수의 값을 변경할 수 없습니다. 최종 수정 변수 .


Const :

"const"는 Dart에서 좀 더 복잡하고 미묘한 의미를 가지고 있습니다. const는 값을 수정 합니다 . const [1, 2, 3]과 같은 컬렉션을 만들 때와 const Point (2, 3)와 같은 객체 (new 대신)를 구성 할 때 사용할 수 있습니다. 여기서 const는 객체의 전체 딥 상태가 컴파일 타임에 완전히 결정될 수 있으며 객체가 고정되고 완전히 불변임을 의미합니다.

Const 객체에는 몇 가지 흥미로운 속성과 제한이 있습니다.

컴파일 타임에 계산할 수있는 데이터에서 만들어야합니다. const 객체는 런타임에 계산해야하는 항목에 액세스 할 수 없습니다. 1 + 2는 유효한 const 표현식이지만 new DateTime.now ()는 그렇지 않습니다.

그들은 깊고 전 이적으로 불변합니다. 컬렉션이 포함 된 최종 필드가있는 경우 해당 컬렉션은 계속 변경할 수 있습니다. const 컬렉션이 있으면 그 안에있는 모든 것이 재귀 적으로 const 여야합니다.

그것들은 표준화되어 있습니다. 이것은 일종의 문자열 interning과 비슷합니다. 주어진 const 값에 대해 const 표현식이 몇 번 평가 되더라도 단일 const 객체가 생성되고 재사용됩니다.


그래서 이것은 무엇을 의미합니까?

Const :
값이 런타임에 계산되는 값인 경우 ( new DateTime.now():) const를 사용할 없습니다 . 그러나 컴파일 타임 ( const a = 1;)에 값이 알려진 경우 constover 를 사용해야합니다 final. const사이에는 두 가지 큰 차이점이 final있습니다. 당신이 사용하는 경우 첫째, const당신은 그것을 선언해야 static const아니라 단지보다 const. 둘째, const컬렉션 이 있다면 그 안의 모든 것이 const. final컬렉션 이 있다면 그 안의 모든 것은 final .

최종 : 컴파일 시간에 값을 모르는 경우 다시
final사용해야하며 const런타임에 계산 / 잡을 것입니다. 변경할 수없는 HTTP 응답을 원하거나 데이터베이스에서 무언가를 가져 오거나 로컬 파일에서 읽으려면 final. 컴파일 타임에 알려지지 않은 것은 모두 final끝났습니다 const.


그 존재의 모든 말한다면, 모두 constfinal재 할당 할 수 없지만 필드 final객체는 한 그렇지 않은 것처럼 const또는 final, (달리 재 할당 할 수 있습니다 const).


통합 @Meyi 및 @ faisal-naseer 답변 및 작은 프로그래밍으로 비교.

const :

컴파일 시간 상수 값 을 저장할 변수를 만드는 데 사용되는 const 키워드 입니다. 컴파일 시간 상수 값은 컴파일하는 동안 상수 값입니다 :-)

예를 들어 5컴파일 시간 상수가 있습니다. 하지만 DateTime.now()이는 컴파일 타임 상수가 아닙니다. 이 메서드는 런타임에 라인이 실행되는 시간 을 반환하기 때문 입니다. 그래서 우리는을 할당 할 수 없습니다 DateTime.now()A를 const변수입니다.

const a = 5;
// Uncommenting below statement will cause compile time error.
// Because we can't able to assign a runtime value to a const variable
// const b = DateTime.now();

같은 줄에서 초기화 해야합니다 .

const a = 5;
// Uncommenting below 2 statement will cause compilation error.
// Because const variable must be initialized at the same line.
// const b;
// b = 6;

아래 언급 된 모든 진술이 허용됩니다.

// Without type or var
const a = 5;
// With a type
const int b = 5;
// With var
const var c = 6;

클래스 레벨 const 변수 는 아래와 같이 초기화해야합니다.

Class A {
    static const a = 5;
}

인스턴스 레벨 const 변수는 불가능합니다 .

Class A {
    // Uncommenting below statement will give compilation error.
    // Because const is not possible to be used with instance level 
    // variable.
    // const a = 5;
}

의 또 다른 주요 용도 const객체를 변경 불가능 하게 만드는 데 사용됩니다 . 클래스 객체를 불변으로 만들려면 생성자함께 const 키워드사용하고 아래에 언급 된 것처럼 모든 필드를 최종적으로 만들어야 합니다.

Class A {
    final a, b;
    const A(this.a, this.b);
}

void main () {
    // There is no way to change a field of object once it's 
    // initialized.
    const immutableObja = const A(5, 6);
    // Uncommenting below statement will give compilation error.
    // Because you are trying to reinitialize a const variable
    // with other value
    // immutableObja = const A(7, 9);

    // But the below one is not the same. Because we are mentioning objA 
    // is a variable of a class A. Not const. So we can able to assign
    // another object of class A to objA.
    A objA = const A(8, 9);
    // Below statement is acceptable.
    objA = const A(10, 11);
}

목록에 const 키워드를 사용할 수 있습니다 .

const a = const []- a 초기화constconst 된 변수 로서 객체 목록을 포함 합니다 (즉, 목록에는 컴파일 시간 상수와 불변 객체 만 포함되어야 함). 따라서 우리는 a다른 목록 으로 할당 할 수 없습니다 .

var a = const []- 목록 객체 를 포함하는 a 초기화varconst 된 변수 입니다. 따라서 변수에 다른 목록을 할당 할 수 있습니다a .

Class A {
    final a, b;
    const A(this.a, this.b);
}

class B {
    B(){ // Doing something }
}

void main() {
    const constantListOfInt = const [5, 6, 7,
                 // Uncommenting below statement give compilation error.
                 // Because we are trying to add a runtime value
                 // to a constant list
                 // DateTime.now().millisecondsSinceEpoch
              ];
    const constantListOfConstantObjA = const [
        A(5, 6),
        A(55, 88),
        A(100, 9),
    ];
    // Uncommenting below 2 statements will give compilation error.
    // Because we are trying to reinitialize with a new list.
    // constantListOfInt = [8, 9, 10];
    // constantListOfConstantObjA = const[A(55, 77)];

    // But the following lines are little different. Because we are just
    // trying to assign a list of constant values to a variable. Which 
    // is acceptable
    var variableWithConstantList = const [5, 6, 7];
    variableWithConstantList = const [10, 11, 15];
    var variableOfConstantListOfObjA = const [A(5, 8), A(7, 9), A(10, 4)];
    variableWithConstantList = const [A(9, 10)];
}

결정적인:

final 키워드는 또한 변수가 상수 값보유 하도록 만드는 데 사용됩니다 . 초기화되면 값을 변경할 수 없습니다.

final a = 5;
// Uncommenting below statement will give compilation error.
// Because a is declared as final.
// a = 6;

아래 언급 된 모든 진술이 허용됩니다.

// Without type or var
final a = 5;
// With a type
final int b = 5;
// With var
final var c = 6;

런타임 값할당 할 수 있습니다.

// DateTime.now() will return the time when the line is getting
// executed. Which is a runtime value.
final a = DateTime.now();
var b = 5;
final c = b;

클래스 레벨 최종 변수 는 동일한 행에서 초기화되어야합니다.

Class A {
    static final a = 5;
    static final b = DateTime.now();
}

인스턴스 수준 최종 변수 는 동일한 줄 또는 생성자 초기화에서 초기화되어야합니다. 값은 개체가 생성 될 때 메모리에 저장됩니다.

Class A {
    final a = 5;
}

// Constructor with a parameter.
Class B {
    final b;
    B(this.b);
}

// Constructor with multiple parameter.
Class C {
    final c;
    C(this.c, int d) {
        // Do something with d
    }
}

void main() {
    A objA = new A();
    B objB = new B(5);
    C objC = new C(5, 6);
}

목록 할당 .

final a = [5, 6, 7, 5.6, A()];
// Uncommenting Below statement will give compilation error.
// Because we are trying to reinitialize the object with another list.
// a = [9.9, 10, B()];

@Meyi의 답변 확장

  • final variable can only be set once and it is initialized when accessed.(for example from code section below if you use the value of biggestNumberOndice only then the value will be initialized and memory will be assigned).
  • const is internally final in nature but the main difference is that its compile time constant which is initialized during compilation even if you don't use its value it will get initialized and will take space in memory.

  • Variable from classes can be final but not constant and if you want a constant at class level make it static const.

Code:

void main() {

    // final demonstration
    final biggestNumberOndice = '6';
    //  biggestNumberOndice = '8';     // Throws an error for reinitialization

    // const
    const smallestNumberOnDice = 1;

}

class TestClass {

    final biggestNumberOndice = '6';

    //const smallestNumberOnDice = 1;  //Throws an error
    //Error .  only static fields can be declared as constants.

    static const smallestNumberOnDice = 1;
}

Const

Value must be known at compile-time, const birth = "2008/12/26". Can't be changed after initialized


Final

Value must be known at run-time, final birth = getBirthFromDB(). Can't be changed after initialized


If you are coming from C++ then const in Dart is constexpr in C++ and final in Dart is const in C++.

The above applies to primitive types only. However in Dart objects marked final are mutable in terms of it's members.


Both final and const prevent a variable from being reassigned (similar to how final works in Java or how const works in JavaScript).

The difference has to do with how memory is allocated. Memory is allocated for a final variable at runtime, and for a const variable at compile-time. The final modifier should be the more commonly used, because many program variables won't need any memory since the program logic won't call for them to be initialized. With a const variable you are basically telling the computer, "Hey, I need memory for this variable up front because I know I'm going to need it."

Thinking of them in this way makes it easier to understand differences in their syntactical usage. Mainly that a final variable may be an instance variable, but a const must be a static variable on a class. This is because instance variables are created at runtime, and const variables--by definition--are not. Thus, const variables on a class must be static, which means simply that a single copy of that variable exists on a class, regardless of whether that class is instantiated.

This video breaks it down fairly simply: https://www.youtube.com/watch?v=9ZZL3iyf4Vk

This article goes into more depth and explains a very important semantic difference between the two, i.e. final modifies variables and const modifies values, which essentially boils down to only being able to initialize const values which are derivable at compile-time.

https://news.dartlang.org/2012/06/const-static-final-oh-my.html

참고URL : https://stackoverflow.com/questions/50431055/what-is-the-difference-between-the-const-and-final-keywords-in-dart

반응형