File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Scala and the fly likes Scala Immutability Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » Scala
Bookmark "Scala Immutability" Watch "Scala Immutability" New topic

Scala Immutability

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10032

Scala fans,

After almost 8 months of completing the Functional Programming course on Scala through Coursera, I'm back dusting my knowledge in Scala. I'm using the Scala book from Martin Oedersky.

In Chapter 6, I came across the following example.,

What I fail to understand is that why would that.d and that.n result in a compile time failure?

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10032

After reading a couple of pages further, the obvious becomes more evident. But still I do not get why that.n is not allowed?
Hussein Baghdadi
clojure forum advocate

Joined: Nov 08, 2003
Posts: 3479

What the compiler is telling you?
Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 370

I think this is because the default is for the compiler to create private fields with no accessors so you do not have access to that.n but do have access to this.n (same as in Java when no getter is available), if you want to expose the data you need to declare some fields and assign n and d to them, the equivalent class in Java would be something like:

Maxim Karvonen
Ranch Hand

Joined: Jun 14, 2013
Posts: 117
By default that parameters are treated somewhat like a "constructor parameters" but not "class fields". In some cases they may be not stored as fields (if they are used only in "constructor" code). And it is pretty convenient to access some "instance creation parameters" without manually putting them in some field.

However, your use case is also very common. So Scala have a special syntax to treat "constructor arguments" also as instance fields:

Such declarations are required for each parameter that need to be a field. "private" is not required, you may use any Scala access modifier there.

You may also use "case classes" in some cases. They always have it's "constructro arguments" as fields. But case classes are more specialized thing than general classes.
I agree. Here's the link:
subject: Scala Immutability
It's not a secret anymore!