Kevin Meredith
Kevin Meredith

Reputation: 41939

Value Class w/ `val` Field

Reading the Value Classes and Universal Traits post, I looked at the RichInt example.

But, I changed the self field to leave off the val.

scala> class RichInt(self: Int) extends AnyVal {
     |  def toHexString: String = java.lang.Integer.toHexString(self)
     | }
<console>:7: error: value class parameter must be a val and not be private[this]
       class RichInt(self: Int) extends AnyVal {
                     ^

I got a compile-time error. It appears that omitting the val results in the field have accessibility of private[this].

What's the significance of keeping versus excluding val? I'm not sure what must be a val actually means.

Upvotes: 0

Views: 277

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

Perhaps the wording must be a val is a bit off. More specifically, the value class parameter must be a public val, as stated in that very article.

A value class …

… must have only a primary constructor with exactly one public, val parameter whose type is not a value class.

Declaring class RichInt(val self: Int) extends AnyVal, means that a public accessor for self will be created by the compiler for class RichInt. If you remove the val declaration from within the constructor, then self will be private within instances of the class (and only accessible to this instance).

Upvotes: 3

Related Questions