카테고리 없음

Dart - 다트의 생성자엔 왜 late를 쓰지 않는 걸까?

koldin 2023. 2. 10. 16:14

앱 기반 서비스를 위해 플러터를 배워야 해서 다트 공부부터 시작했다.

근데 자바와 언듯 닮은 느낌이 들었다.

근데 생성자 부분에서 late 를 쓰지 않는 것이다!

 

JAVA로 따지면 필드에 private String name; 이 안되는 건데 그럼 어떻게 하냐?

class Player {
  final String name = 'jisoung';
  final int age = 17;

  Player(String name, int age);
  void sayName() {
    print("Hi my name is $name");
  }
}

위와 같이 코드를 짜게 된다.

 

late 는 결국 init을 바로 할 필요 없게 설정하는 것이다.

즉 late가 없을 땐 생성과 동시에 값이 있어야 하는 것이다.

하지만 Class는 인스턴스 생성시 init을 진행하기에 생성자에서 값을 받아 init을 진행하면 

late를 사용하지 않은 것과 크게 다를 바가 없는 것이다.

 

요약하자면

late - 생성 초기가 아닌 추후 최초값 설정 가능

생성자 - 생성 초기가 곧 생성자가 쓰이는 때 이므로 생성자 호출 -> 변수 초기화

 

추가로 아래 스택오버플로우에선 late를 가급적 피하길 권장한다고 하기도 한다.

 

참고:

https://nomadcoders.co/dart-for-beginners/lectures/4114

 

All Courses – 노마드 코더 Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co

https://stackoverflow.com/questions/66753800/dart-which-is-a-better-practice-using-late-or-constructor-initializer-list

 

Dart: Which is a better practice? Using 'late' or constructor initializer list

I am modelling a Dart class with the new null safety types in mind. I believe there are two effective ways to initialize non-nullable properties, calculated from a parameter. For this example, we w...

stackoverflow.com