널 인식 접근
Coddy Dart 여정의 기초 섹션에 포함된 레슨 — 94개 중 29번째.
null 인식 접근 연산자 (?.)는 잠재적으로 null인 객체의 속성에 안전하게 접근하여 런타임 오류를 방지합니다.
void main() {
String? name = 'Dart';
int? length = name?.length;
print('Name: $name');
print('Length: $length');
}null 값이 있을 때, 크래시 대신 null을 반환합니다:
void main() {
String? name = null;
int? length = name?.length;
print('Name: $name');
print('Length: $length');
}챌린지
쉬움게임 캐릭터와 함께 null-aware access operator(?.)를 demonstrating하는 Dart 프로그램을 생성하세요:
playerName이라는 이름의 null이 될 수 있는 String 변수를 생성하고 null로 설정하세요playerScore이라는 이름의 null이 될 수 있는 int 변수를 생성하고 100으로 설정하세요- null-aware access operator(
?.)를 사용하여 playerName의 길이를 가져와nameLength이라는 변수에 저장하세요 - 다음 메시지를 출력하세요:
Player name length: X(여기서 X는 nameLength의 값입니다) playerName을 "Champion"으로 업데이트하세요- null-aware access operator를 다시 사용하여 업데이트된 길이를 가져와
nameLength에 저장하세요 - 업데이트된 메시지를 출력하세요:
Player name length: X(여기서 X는 새로운 값입니다) - 다음 형식으로 플레이어의 점수를 출력하세요:
Player score: 100
치트 시트
null-aware 접근 연산자 (?.)는 잠재적으로 null인 객체의 속성에 안전하게 접근하여 런타임 오류를 방지합니다.
객체가 null이 아닐 때, 속성 값을 반환합니다:
String? name = 'Dart';
int? length = name?.length; // 4를 반환합니다객체가 null일 때, 충돌하는 대신 null을 반환합니다:
String? name = null;
int? length = name?.length; // null을 반환합니다직접 해보기
void main() {
// 여기에 nullable 변수를 선언하세요
String? playerName = _;
int? playerScore = _;
// ?. 연산자를 사용하여 playerName의 길이 가져오기
int? nameLength = playerName_.length;
// 초기 이름 길이 출력
print("Player name length: ${nameLength}");
// playerName 업데이트
playerName = _;
// ?. 연산자를 사용하여 업데이트된 길이 가져오기
nameLength = playerName_.length;
// 업데이트된 이름 길이 출력
print("Player name length: ${nameLength}");
// 플레이어의 점수 출력
print("Player score: ${playerScore}");
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.