728x90

The instanceof-operator is called is in Dart.

is : 같은 타입이면 true

is! : 다른 타입이면 true

 

main() {
  int x = 10;
  // is 키워드를 사용하면, 해당 참조가 주어진 타입인지 검사
  if(x is int){
    print('정수');
  }
}

 

void main() {
  var value = 2;
  print(value is int);
  print(value is! int);
}

 

 

class Foo {
  @override
  Type get runtimeType => String;
}
 
main() {
  var foo = Foo();
  if (foo is Foo) {
    print("It's a foo!");
  }
  print("Type is ${foo.runtimeType}");
}

 

 

To check the type of a variable in Flutter and Dart, you can use the runtimeType property.

플러터와 다트에서 변수의 타입을 검사하기 위해, runtimeType 프로퍼티를 사용할 수 있다.

void main(){
  var a = 'Apple';
  var b = 100;
  var c = [12345];
  var d = {
    "name""John Doe",
    "age" : 40
  };
  var e = 1.14;
  
  print(a.runtimeType);
  print(b.runtimeType);
  print(c.runtimeType);
  print(d.runtimeType); 
  print(e.runtimeType);
}

 

class Person {
  var s = '홍길동';
  var d = 5.5;
  var r = true;
}
 
main() {
  Person p = Person(); // new 생략 가능
  print('Data type of s : ${p.s.runtimeType}');
  print('Data type of d : ${p.d.runtimeType}');
  print('Data type of r : ${p.r.runtimeType}');
}

 

class Shape {
  String color;
  Shape({required this.color}); // 생성자
}
 
class Circle extends Shape {
  double radius;
  Circle({color, required this.radius}) : super(color: color);
}
 
class Rectangle extends Shape {
  double length;
  double width;
  Rectangle({color, required this.length, required this.width}) : super(color: color);
}
 
void main() {
  Circle circle = Circle(color: 'red', radius: 10);
 
  print(circle is Circle); // true
  print(circle is Shape); // true
  print(circle is Rectangle); // false
}

참조 : https://www.woolha.com/tutorials/dart-getting-runtime-type-of-object

 

 

assert() 함수는 계산 결과가 참인지 거짓인지 검사한다.

https://dartpad.dartlang.org/ 사이트에서는 동작되지 않더라.

 

'Flutter 앱 > Dart 언어' 카테고리의 다른 글

Dart Class(클래스)  (0) 2022.06.27
Dart Asynchronous programming(비동기 프로그래밍)  (0) 2022.06.23
Dart function(함수)  (0) 2022.06.22
Dart const, final  (0) 2022.06.22
Dart 변수 var, dynamic, num, int, double  (0) 2022.06.22
블로그 이미지

Link2Me

,