본문 바로가기
개발일지/임시카테고리

dart - class generic 다트 - 클래스 제네릭 6

by 다니엘의 개발 이야기 2025. 3. 24.
320x100
void main() {
  // 여기서 <>안에 들어간 String도 generic이다.
  List<String> names = [];
  
  Lecture<String> lecture1 = Lecture('123', 'lecture1');
  
  lecture1.printIdType();
  
  Lecture<int> lecture2 = Lecture(123, 'lecture2');
  
  lecture2.printIdType();
  
}

// generic - 타입을 외부에서 받을때 사용

// 그냥 <>안에 뭐라도 넣어주면 된다.
// Lecture옆에 <>안에 T,A이런식으로 들어가게 되면, 타입이 2개 들어가게 되고,
// 파라미터에 값이 들어가는 첫번째 타입이 T에 지정되고, 두번째 타입이 A에 들어가게 된다.
class Lecture<T> {
  final int id;
  final String name;
  
  Lecture(this.id, this.name);
  
  
  void printIdType(){
    print(id.runtimeType);
  }
}
300x250