객체의 타입 확인
A tour of the Dart language 페이지를 공부하면서 정리한 내용입니다.
런타임에 객체의 타입을 확인하려면 Type 객체를 반환하는 Object
클래스의 runtimeType
속성을 사용합니다.
class ImmutablePoint {
final int x;
final int y;
const ImmutablePoint(this.x, this.y);
}
void main() {
var a = const ImmutablePoint(1, 1);
print('The type of a is ${a.runtimeType}');
}
runtimeType
속성 대신 타입 테스트 연산자를 이용해 객체의 유형을 검사하세요. 프로덕션 환경에서 object is Type
검사 object.runtimeType == Type
검사보다 더 안정적입니다.
class ImmutablePoint {
final int x;
final int y;
const ImmutablePoint(this.x, this.y);
}
void main() {
var a = ImmutablePoint(1, 1);
print('a is ImmutablePoint? ${a is ImmutablePoint}');
dynamic b = ImmutablePoint(2, 3);
if (b is ImmutablePoint) {
print('b.x=${(b as ImmutablePoint).x}, b.y=${(b as ImmutablePoint).y}');
}
}
Last updated