A
A
Andrey Kondratiev2015-09-22 23:48:51
Scala
Andrey Kondratiev, 2015-09-22 23:48:51

How do val parameters with the same name as parameterless methods work in Scala?

Let's say we have the following code in the scala worksheet:

class Point (val x: Int, val y: Int)

trait Rectangular {
  def topLeft: Point
  def bottomRight: Point
  def left = topLeft.x
  def right = bottomRight.x
  def width = right - left
  override def toString = topLeft.x + ", " + topLeft.y + " - " + bottomRight.x + ", " + bottomRight.y
}

class Rectangle(val topLeft: Point, val bottomRight: Point) extends Rectangular

val rect = new Rectangle(new Point(1,1), new Point(10, 10))
//rect: Rectangle = 1, 1 - 10, 10

rect.width
//res0: Int = 9

It is not entirely clear how part of the code in the Rectangle class is revealed. The documentation says that we cannot have a field and a parameterless method with the same name in the same class. This begs the question, what happens to the topLeft and bottomRight functions when the Rectangle class is defined?
I believe the Rectangle class actually means the following
class Rectangle(override val topLeft: Point, override val bottomRight: Point) extends Rectangular

and override are simply omitted because the original methods in Rectangular are abstract.
How can you explain what is happening in this code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Smirnov, 2015-09-23
@Andruhon

Design

class Rectangle(val topLeft: Point, val bottomRight: Point)

implies that a constructor with topLeft, bottomRight parameters will be generated for the class, corresponding fields will be created in the class, and getters with the same names will be generated for these fields.
In the case when we refer to the field, in fact, we still refer to the getter. And in this case, this getter will have a corresponding description that matches def topLeft: Point.
Accordingly, no contradictions arise, we have a getter that fits the interface of the class from which we are inheriting. If we declare a class, for example, as:
That program will not compile, respectively.
If you go deeper, then in fact the rock tries to distinguish between val and def. These are both equal ads. The difference between them lies in the execution strategy. Read more:
https://class.coursera.org/progfun-005/lecture/4
https://class.coursera.org/progfun-005/lecture/5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question