2022년 10월 26일 수요일

[Flutter] mutable 과 immutable 에 대해서

 Dart 언어에서 뿐만 아니라, 다른 개발 언어에서도, 마찬가지로 알고 가야 할 개념인

mutable과 immutable 개념을 알아보자


mutable  : 변경가능, immutable : 변경 불가능


예를 들어, 

class Car {
int? id;
String? model;

Car({this.id, this.model});
}

void main() {
Car car = Car(id:1, model:'m1');
Car car2 = car;

print('car, id=${car.id}, model=${car.model}');

car2.model = 'm2';

print('car2, id=${car.id}, model=${car.model}');
print('car, id=${car.id}, model=${car.model}');
}

결과값

car, id=1, model=m1
car2, id=1, model=m2
car, id=1, model=m2

car2 에 car를 받아서, car2의 변수를 변경했는데, car2 의 model 변수 뿐아니라,

car의 model 변수 값도 변경되었다.

이경우, car의 주소값이 car2에게 복사 된것이므로 같은 주소값을 가지고 있기때문이다, 그래서 car 객체 변수는 mutable 한 것 이다.


car2를 다른 주소값으로 갖게하게끔 Car객체를 생성하고 싶다면,

Car car2 = car;

대신, Car car2 = Car(id:1, model:'m2'); 라고 새로 객체를 생성해주면, car와 별개의 주소값

을 갖게된다.


다른예로,

final name1 = 'David';

const name2 = 'Paul';

둘다, immutable에 해당하는 변수 이다.

값을 할당하면, 다시 변경 불가능한 변수가 되게 final과 const를 붙였기 때문이다.ㅏ

final과 const는 값이 할당되는 시점의 차이가 있다.

final은 컴파일 이후, 런타임 에서 값을 할당 할 수 있다.

그러나 한번 할당 된 값은 변수가 초기화 되기전에는 다시 다른 값으로 변경불가하다.

const는 컴파일 될 때, 값을 할당되는 것이다. 따라서, 런타임 시에는 더이상 값을 할당할수 가 없다.


---- English ----


Not only in Dart language, but in other development languages as well, it is a concept that you need to know.


Learn the concepts of mutable and immutable


mutable : mutable, immutable : immutable


for example,

class Car {
int? id;
String? model;

Car({this.id, this.model});
}

void main() {
Car car = Car(id:1, model:'m1');
Car car2 = car;

print('car, id=${car.id}, model=${car.model}');

car2.model = 'm2';

print('car2, id=${car.id}, model=${car.model}');
print('car, id=${car.id}, model=${car.model}');
}

result

car, id=1, model=m1
car2, id=1, model=m2
car, id=1, model=m2


I received car in car2 and changed the variable of car2, not only the model variable of car2,

The value of the model variable of car has also been changed.

In this case, the car's address value is copied to car2, so it has the same address value, so the car object variable is mutable.


If you want to create a Car object so that car2 has a different address value,

Car car2 = car;

Instead, Car car2 = Car(id:1, model:'m2'); If you create a new object with

will have


In another example,


final name1 = 'David';

const name2 = 'Paul';

Both are variables that are immutable.


This is because when you assign a value, it becomes final and const so that it becomes an immutable variable again.


The difference between final and const is when a value is assigned.


final can be assigned a value at runtime after compilation.


However, the value assigned once cannot be changed to another value until the variable is initialized.


const is a value assigned at compile time. Therefore, it is no longer possible to assign a value at runtime.





댓글 없음:

댓글 쓰기