flutter로 계산하다 보면 == 연산자와 is 연산자를 종종 사용하게 되는데 어떤때에 == 연산자를 사용하고 is 연산자를 사용하는지 알아보자.
== Operator
공식 사이트를 보면
The default behavior for all Objects is to return true if and only if this object and other are the same object.
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects o, o == o must be true.
Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.
Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.
라고 나와 있는데 결국 객체가 같은지 보는것이라고 한다.
is
is 의 같은 경우는 객체를 검사하는것이 아닌 타입을 검사하는 것이다.
is 키워드 : 같은 타입이면 true를 반환하고 다른 타입이면 false를 반환.
is! 키워드 : 같은 타입이면 false를 반환하고 다른 타입이면 true를 반환.
간단한 예제 1
void main() {
int a1= 1;
int a2 = 2;
int a3 =1 ;
print(a1 == a2);
print(a1 == a3);
print(a1 == int);
}
false
true
false
간단한 예제 2
int a1 = 1;
double a2 = 2.2;
print(a1 is int);
print(a1 is double);
print(a2 is int);
print(a2 is double);
true
true
false
true
오류 1
int a1 = 1;
double a2 = 2.2;
print(a1 is a2);
Error: 'a2' isn't a type.
print(a1 is a2);
^^
Error: Compilation failed.
a2는 타입이 아니기 때문에 is 키워드를 사용시 에러가 난다.