Renz
Renz

Reputation: 37

Data Abstraction in Scala

enter image description hereWe were given a problem in scala to define a procedure that that takes a line segment as an argument and returns its midpoint(the point whose coordinates are the average of the coordinates of the end points.) When I try to compile the program it gives me two errors, namely type mismatch errors in my midpointSegment method. I don't get why it requires a String. Can anyone point out my mistake? Below is my code.

class Point(x: Int, y: Int) {
  def xCoord = x
  def yCoord = y    

  def makeString(m: Point) = "Point" + "(" + x + "," + y + ")" 
}

class LineSegment(x: Point, y: Point) {
  def startSeg = x
  def endSeg = y

  def midpointSegment(m: LineSegment) = ((startSeg + m.startSeg) / 2, 
    (endSeg + m.endSeg) / 2)

  def makeString(m: LineSegment) = 
    "LineSegment" + "(" + x.makeString(x) + "," + y.makeString(y) + ")"
}

object Mp5 {
  def main(args: Array[String]): Unit = {   
    val aLine1 = new Point(1, 2)
    val aLine2 = new Point(5, 4)
    val aLineSegment1 = new LineSegment(aLine1, aLine2)
    val aLineSegment2 = new LineSegment(new Point(-3, 5), new Point(8, -1))

    println(aLine1.makeString(aLine1))
    println(aLine2.makeString(aLine2))
    println(aLineSegment1.makeString(aLineSegment1)) 
    println(aLineSegment2.makeString(aLineSegment2))

    println(aLineSegment1.midpointSegment(aLineSegment2))
  }
}

Upvotes: 0

Views: 347

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170919

You are trying to add two points, since startSeg and m.startSeg are points. You haven't defined how to do this, so the compiler seems to think you are adding strings (since anything can be added to a string, as in definition of toString). To be honest, I wouldn't expect this error if that's the entire code, and instead something about a missing + method.

For future reference: 1. provide the actual error message and stack trace; 2. you don't need to define methods like def xCoord = x in Scala, just write val x instead of simply x in class parameters; 3. read about case classes.

Upvotes: 2

Related Questions