Scala没有返回正确的值

时间:2014-08-10 01:19:53

标签: scala

所以我试图运行此代码,但是当我尝试打印LineSegment时,它无法正确显示。

println(aLineSegment1.makeString(aLineSegment1))

给出>LineSegment@77c2bc0d

知道如何解决这个问题吗?

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 makeString(m: LineSegment) = 
        "LineSegment" + "(" + x + "," + 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)) 
    }
}

1 个答案:

答案 0 :(得分:1)

您未使用Point方法调用makeString()的{​​{1}}方法。您可以通过进行以下更改来实现此目的:

LineSegment.makeString()

但是,在Java / Scala中,覆盖对象到字符串转换的toString()方法是常规的。如果你这样做,转换将自动调用,而不必自己调用该方法。

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