Scala类型与嵌套函数调用不匹配

时间:2016-10-06 16:17:19

标签: scala types

我有这个代码,我似乎无法开始工作。该代码应该允许您确定圆和矩形的边界框是否相互重叠。

    abstract class Shape
    case class Circle(r: Double, x: Double, y: Double) extends Shape
    case class Rectangle(llx: Double, lly: Double, w:Double, h:Double) extends Shape


 def boundingBox(s: Shape): Rectangle = s match {
      case Rectangle(llx, lly, w, h) => Rectangle(llx, lly, w, h)
      case Circle(r,x,y) => Rectangle(x-r, y-r, 2*r, 2*r)
    }


    def mayOverlap(s1: Shape, s2: Shape) = overlapRect(boundingBox(s1), boundingBox(s2))

    def overlapRect(r1: Rectangle, r2: Rectangle) = betweenLine(r1.llx, r1.w, r2.llx, r2.w) && betweenLine(r1.lly, r1.h, r2.lly, r2.h)

    def betweenLine(x: Double, l: Double, a: Double, k: Double): Boolean = (a <= x+l) || (a+l <= x+l)

除了mayOverlap之外,所有功能都正常运行。当我将这些函数加载到解释器中时,我得到以下错误:

<console>:63: error: type mismatch;
 found   : Rectangle(in object $iw)
 required: Rectangle(in object $iw)
       def mayOverlap(s1: Shape, s2: Shape) = overlapRect(boundingBox(s1), boundingBox(s2))
                                                                     ^
<console>:63: error: type mismatch;
 found   : Rectangle(in object $iw)
 required: Rectangle(in object $iw)
       def mayOverlap(s1: Shape, s2: Shape) = overlapRect(boundingBox(s1), boundingBox(s2))

我对scala很新,我对haskell更熟悉所以我可能会假设两者之间的相似性,但我试图将其简化,我似乎无法做出任何在mayOverlap中完全嵌套函数调用。

1 个答案:

答案 0 :(得分:0)

我通过重新排序函数声明来解决问题,因此嵌套的辅助函数首先出现。