0

I am newbie to scala and is a bit confused about some of its usage. Can "object private" fields (private[this]) in scala be thought as ThreadLocal in java? (Every object have their own copy).

Prateek
  • 523
  • 2
  • 13
  • 2
    For a ThreadLocal every object does *not* have their own copy. It's more like a global variable, really (local to the thread, but accessible globally from everywhere on that thread). – Thilo Sep 19 '13 at 06:01

1 Answers1

0

You are mistaken. With private[this], you can only access that member from within that object (§5.3):

An different form of qualification is private[this]. A member M marked with this modifier can be accessed only from within the object in which it is defined.

But still multiple threads can make changes to that object at the same time i.e. because they can still access it. Where as with ThreadLocal you have the object binded to the thread and not the object. So unlike former, each thread has its own respective object and cannot access the other thread's local assigned object.

Simply put, with private[this]- variable is associated with that object in the second with the thread. Moreover they are very different also from encapsulation point of view.

Jatin
  • 31,116
  • 15
  • 98
  • 163
  • is there any use of this? I tried hard to think of the use-case, where it can make sense but... – Prateek Sep 19 '13 at 06:21
  • Well it has some very small use cases. For example you wish to have `equals` where you dont want someone to access: `class A{ private [this] val i = 23 def checkEqual(p:A) = { p.i// you cannot access variable i of p } }` – Jatin Sep 19 '13 at 07:04
  • 2
    @Prateek you might want to see this: http://stackoverflow.com/questions/9698677/privatethis-vs-private – Jatin Sep 19 '13 at 07:10