Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In Scala the parameters of the constructor become public attributes of the class if declared as a <code>var</code> or <code>val</code>.</p> <pre><code>scala&gt; class Point(val x: Int, val y: Int){} defined class Point scala&gt; val point = new Point(1,1) point: Point = Point@1bd53074 scala&gt; point.x res0: Int = 1 scala&gt; point.y res1: Int = 1 </code></pre> <p><strong>Edit to answer the question in comments</strong> "if they were private fields, shouldn't my first code snipped after the edit have worked?"</p> <p>The constructor <code>class Point(x: Int, y: Int)</code> generates <em>object-private</em> fields which only allow methods of the <code>Point</code> class to access the fields <code>x</code> and <code>y</code> not other objects of type <code>Point</code>. <code>that</code> in the <code>+</code> method is another object and is not allowed access with this definition. To see this in action define add a method <code>def xy:Int = x + y</code> which does not generate a compile error.</p> <p>To have <code>x</code> and <code>y</code> accessible to the class use a <em>class-private</em> field which is as follows:</p> <pre><code>class Point(private val x: Int, private val y: Int) { def +(that: Point): Point = new Point(this.x + that.x, this.y + that.y) } </code></pre> <p>Now they are not accessible outside of the class:</p> <pre><code>scala&gt; val point = new Point(1,1) point: Point = Point@43ba9cea scala&gt; point.x &lt;console&gt;:10: error: value x in class Point cannot be accessed in Point point.x ^ scala&gt; point.y &lt;console&gt;:10: error: value y in class Point cannot be accessed in Point point.y </code></pre> <p>You can see this in action by using <code>scalac -Xprint:parser Point.scala</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload