【问题标题】:scala error ambiguous reference to overloaded definitionscala错误对重载定义的模糊引用
【发布时间】:2016-08-12 19:26:31
【问题描述】:

我是 scala 的新手,正在尝试学习 scala。 我正在尝试编写以下 2 个类,但出现以下错误。 请帮帮我

scala> class Point(val x: Int,val y: Int)
defined class Point

scala> class Rectangle(val topleft: Point,val bottomright: Point){
     | def topleft: Point
     | def bottomright: Point
     | def left=topleft.x
     | def right=bottomright.x
     | def width=right-left
     | }


<console>:14: error: ambiguous reference to overloaded definition,
both value topleft in class Rectangle of type => Point
and  method topleft in class Rectangle of type => Point
match expected type ?
       def left=topleft.x
                ^


<console>:15: error: ambiguous reference to overloaded definition,
both value bottomright in class Rectangle of type => Point
and  method bottomright in class Rectangle of type => Point
match expected type ?
       def right=bottomright.x
                 ^
<console>:13: error: value bottomright is defined twice
  conflicting symbols both originated in file '<console>'
       def bottomright: Point
           ^

<console>:12: error: value topleft is defined twice
  conflicting symbols both originated in file '<console>'
       def topleft: Point

感谢和问候,

【问题讨论】:

    标签: scala


    【解决方案1】:

    您已经定义了两次topleftbottomright。只需删除以下两行即可修复错误:

    def topleft: Point
    def bottomright: Point
    

    【讨论】:

    • 感谢 marstran,我只想知道课堂上的 1 个细节我使用了 val topleft: Point,val bottomright: Point as vals 和 def topleft: Point | def bottomright:指向方法,在scala中我们不能为val和def使用相同的名称,它们是方法
    • 不,你不能。当你提到它时,你怎么知道哪个是哪个? def 只是一个表达式,每次使用时都会对其进行评估。 val 是一个只计算一次的表达式,并且会立即发生。
    【解决方案2】:

    请定义 Rectangle 类如下,不带 topleft 和 bottomright:-

    scala> class Rectangle(val topleft: Point,val bottomright: Point){
         | def left=topleft.x
         | def right=bottomright.x
         | def width=right-left
         | }
    defined class Rectangle
    

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多