1

I have noticed the operator ^ in dart which never seen before. Its being use in calculating the hashcode see below for details. Here is a code snippet, check the section hashcode where i saw:

import './color.dart';
import './colors.dart';

class CoreState {
  final int counter;
  final Color backgroundColor;

  const CoreState({
    this.counter = 0,
    this.backgroundColor = Colors.white,
  });

  CoreState copyWith({
    int? counter,
    Color? backgroundColor,
  }) =>
      CoreState(
        counter: counter ?? this.counter,
        backgroundColor: backgroundColor ?? this.backgroundColor,
      );

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is CoreState &&
              runtimeType == other.runtimeType &&
              counter == other.counter &&
              backgroundColor == other.backgroundColor;

  @override
  int get hashCode => counter.hashCode ^ backgroundColor.hashCode;


  @override
  String toString() {
    return "counter: $counter\n"
            "color:$backgroundColor";
  }
}
Solen Dogan
  • 139
  • 8

3 Answers3

2

The Dart Language Tour explains that ^ is bitwise XOR. This operator is typically used for computing hash codes. For an explanation why see Why is XOR often used in Java hascode...

Patrick O'Hara
  • 1,999
  • 1
  • 14
  • 18
  • THanks Patrick, this link explains well indeed. Otherwise it didnot make sense to me using the XOR operator for hashcodes – Solen Dogan Jul 26 '21 at 12:28
2

The ^ operator in Dart stand for XOR.

For more details, check this

Benedict
  • 441
  • 4
  • 14
1

In Dart, the ^ operator is a user-definable operator.

The traditional use of it is exclusive-or (XOR) of integers and Booleans.

var x = 170;
x = x ^ 85;
print(x); // 255;
x ^= 85;  // Same meaning as `x = x ^ 85;`.
print(x); // 170

and

var oddity = false;
for (var number in someNumbers) {
  oddity ^= element.isOdd;
}
// True if an odd number of numbers are odd.

You can implement the ^ operator on your own classes too. For example the BigInt and Int32x4 classes do, with similar XOR-based meaning.

You could also use it for different things, say matrix exponentiation:

class Matrix {
  // ...
  Matrix operator ^(int power) {
    RangeError.checkNotNegative(power, "power");
    if (this.height != this.width) {
      throw UnsupportedError("Can only do exponents of square matrices");
    }
    var result = Matrix.identity(this.height);
    while (power > 0) { // Can be made more efficient!
      result *= this;  
      power -= 1;
    }
    return result;
  } 
}
...

  var matrix = otherMatrix ^ 2;

The precedence of the operator is always the same (just between & and |).

lrn
  • 64,680
  • 7
  • 105
  • 121
  • Thats a very helpful example thanks aot, never thought of operator overloading. I will try your code snippet now Good job my friend – Solen Dogan Jul 30 '21 at 06:28