Skip to content

dynamic type 인자로 받고 있는 메서드 개선 #790

@violet-dev

Description

@violet-dev
// 1. 봉인된 클래스 (Sealed Class)를 정의하여 상속받는 타입을 제한합니다.
sealed class StringOrInt {} 

// 2. String과 int를 감싸는 랩퍼 클래스를 정의합니다.
class MyString implements StringOrInt {
  final String value;
  MyString(this.value);
}

class MyInt implements StringOrInt {
  final int value;
  MyInt(this.value);
}

// 3. 제네릭 T의 상한을 StringOrInt로 제한합니다.
class MyContainer<T extends StringOrInt> {
  final T data;
  MyContainer(this.data);

  void printType() {
    // 내부에서는 'switch'를 사용하여 컴파일 타임에 모든 케이스를 강제할 수 있습니다.
    switch (data) {
      case MyString s:
        print('String data: ${s.value}');
        break;
      case MyInt i:
        print('Int data: ${i.value}');
        break;
    }
  }
}

void main() {
  // ✅ 성공: StringOrInt의 서브타입만 허용
  var sContainer = MyContainer(MyString('hello'));
  sContainer.printType(); // String data: hello

  var iContainer = MyContainer(MyInt(123));
  iContainer.printType(); // Int data: Int data: 123

  // ❌ 에러 발생: double은 StringOrInt의 서브타입이 아니므로 컴파일 에러
  // var dContainer = MyContainer(double.parse('1.0')); 
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions