Scala: method\operator overloading

前端 未结 3 1323
陌清茗
陌清茗 2020-12-05 04:53

The following example is from the book \'Programming in Scala\'. Given a class \'Rational\' and the following method definition:

def add(that: Rational): Rat         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 05:26

    You haven't specified the binary + operator, you've specified the unary + operator.

    So instead of:

    def +(that: Int): Rational =
      +(new Rational(that, 1))
    

    You need to write this:

    def +(that: Int): Rational =
      this +(new Rational(that, 1))
    

提交回复
热议问题