coutier eric
coutier eric

Reputation: 1019

why identical() return true on two strings

I'm new to Dart. The documentation say: "To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.)"

So, if type this code:

var foo = 'bar';
var baz = 'bar';
print(identical(foo, baz));

If i've well understood, foo and bar do not reference the same object. So identical() must return false, isn't it ? But it's not the case, at least in DartPad.

Where is the problem.

Upvotes: 0

Views: 335

Answers (2)

lrn
lrn

Reputation: 71743

In this case foo and bar do reference the same object. That is because the compiler canonicalizes string literals.

The specification requires most constants to be canonicalized. If you create const Duration(seconds: 1) in two places, it will become the same object. Integers, doubles and booleans are always canonicalized, whether constant or not (the language pretends that there is only one instance per value).

Strings are special in that the specification is not entirely clear on whether they need to be canonicalized or not, but constant strings need to be canonicalized for constants to make sense, and all the compilers do that. A literal is a constant expression, so string literals are always canonicalized. That means that 'bar' denotes the same object no matter where it occurs in your code.

Upvotes: 3

Kevin Moore
Kevin Moore

Reputation: 6171

For several built-in "literals", you will always get identical true for equal values.

  • bool
  • String
  • int
  • double (I think)

Upvotes: 1

Related Questions