Dart 언어에는 Null-Safety라는 개념이 존재한다.
Null-Safety 는 변수의 초기화와 깊은 관련이 있는데, 코드로 확인해보자
int notnull = 3;
print(notnull);
>> 3 정상출력
int notnull_notInit;
print(notnull_notInit);
>> Non-nullable varaiable must be assigned before it can be used.
초기화되지 않은 정수 변수를 출력하려고 하니 에러가 발생한다.
null을 가질 수 없는 객체는 사용되기전에(매개변수로 전달되거나 하는) 초기화되어야한다는 의미인데,
말 그대로
초기화되지 않았으니 null이라고 우선 칠까? X
초기화되지 않았고 null을 허용하지 않는 변수이므로 초기화되기 전에 사용되면 짖을거야! O
int? nullable = 3;
int? nullable_notInit;
print(nullable);
print(nullable_notInit);
nullable_notInit.abs();
int? 변수는 null값을 허용하는 정수형 변수로, 이번엔 초기화하지 않은 채 사용하려고하면 에러가 발생하지않는다.
초기화되지 않았으니 null이라고 우선 칠까? O
이제 문제는 코드 마지막줄에서 abs()메서드를 호출할때인데, null의 절댓값? 어떤 결과가 나올 지 궁금한데...
Error: Method 'abs' cannot be called on 'int?' because it is potentially null
결과는 abs 클래스는 'int?'클래스에서 호출될수 없다는 에러가 뜬다.
왜냐하면 초기화되지 않은 int? 변수는 null값을 가지며 null의 정체는 Null클래스이기 때문이다!.
서론이 길었는데, 이 Null클래스를 다루는 문법들을 소개하려고한다.
1. ??
A ?? B
만약 A가 null이 아니면 A, null이면 B 즉,
A == null ? A : B
이걸 줄인거다. 별다줄
2. ??=
A = (B ??=C)
1번의 대입버젼
3. ?.
nullable_notInit?.abs()
아까의 예제에서 . (dot) 대신 ?.를 사용하여 메소드를 호출하면 nullable_notInit 변수가 null이 아닐 경우에만 실행되며, null인경우 결과값을 null로 처리한다.
4. !
map['key'].length;
map['key']!.length
nullable 타입이 null이 아님을 확신할 수 있을 때 null이 아니니 안심하고 실행하라고 컴파일러에게 알리는 용도.