prosseek
prosseek

Reputation: 190979

Unique id for Scala object

In Python, id(x) gives the unique id of object x. What's the equivalence in Scala?

>>> id(True)
1166096
>>> id(False)
1166108
>>> x = id([1,2,3])
>>> id(x)
2058589988
>>> y = id([1,2,3])
>>> id(y)
2058589976

I could use x.hashCode for the id, but it will return the same value when the contents are the same. I'd like to know what makes a eq b == false in the following code. What values are compared in a eq b?

scala> val a = ArrayBuffer(1,2,3)
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> val b = ArrayBuffer(1,2,3)
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> a.hashCode
res44: Int = 387518613

scala> b.hashCode
res45: Int = 387518613

scala> a eq b
res39: Boolean = false

Upvotes: 7

Views: 6544

Answers (2)

user1804599
user1804599

Reputation:

It is not possible to do this. You need to generate and keep track of IDs yourself.

eq compares references, and is similar to == in Java.

There is System.identityHashCode (which is the default implementation of Any.hashCode) but it is not guaranteed to be unique.

You may be able to implement id using the JNI, although it might not be trivial due to the possibility of a compacting GC being in place. I don't know much about the JNI, though.

Even then, I don't see id as a useful function and I don't see any use for it. If you need a reference to an object, store a reference. If you need a weak reference, use a java.lang.ref.WeakReference[T].

Upvotes: 8

vptheron
vptheron

Reputation: 7466

I could use x.hashCode for the id, but it will return the same value when the contents are the same.

First of all: no. As per the documentation: "The default hashing algorithm is platform dependent." So do not make any assumption on hashCode.

Second: eq compares references. As per the documentation: "Tests whether the argument (arg0) is a reference to the receiver object (this)."

Third: you can't get the equivalent of the python id in scala.

Upvotes: 3

Related Questions