【问题标题】:Override "operators" and println method in Scala在 Scala 中覆盖“运算符”和 println 方法
【发布时间】:2019-04-07 22:33:29
【问题描述】:

我需要为不同类型的基本操作创建方法,因此表达式的输出:println(1 + 2*I + I*3 + 2)3+5i。我是 Scala 的新手,到目前为止,这是我所拥有的:

class IClass() {

  var value = 0
  def *(number: Int): String = {
    //value += number
    value + "i"
  }

}

object ComplexNumbers {

  var TotalValue: Int = 0
  var TotalString: String = ""
  // ...

  def Complex(num1: Int, num2: Int): String ={
    num1 + "+" + num2 + "i"
  }

  implicit class IntMultiply(private val a: Int) extends AnyVal {

    def + (b: String)= {
      if(b.contains("i")){
        TotalValue += a
        TotalString.concat(b)
      }
    }

    def * (b: IClass) = {
      //b.value += a
      a + "i"
    }
  }

  implicit class StringAdd(private val a: String) extends AnyVal {
    def + (b: String): String = {
      if(b.contains("i")){

      }
      a + "i"
    }
  }

  def main(args: Array[String]) {

    println(Complex(1,2)) // 1+2i

    val I = new IClass()
    println(1 + 2*I + I*3 + 2) // 3+5i

    // val c = (2+3*I + 1 + 4*I) * I
    // println(-c) // 7-3i
  }
}

我认为我走错了方向,因为通过在类型上实现这些操作方法,我在 println:Type Mismach 中得到一个错误,因为Any 返回类型我只更新字段而不返回任何内容。知道如何实现吗?

【问题讨论】:

    标签: scala operators


    【解决方案1】:

    您应该将复数视为具有某些行为的类,并首先对其进行定义,而不是专注于您目前所追求的一个具体的副作用。这似乎违反直觉,但实现一个更抽象/一般的问题通常比试图将其缩小到手头的任务更容易。

    case class ComplexInt(real: Int, im: Int) {
       def + (other: ComplexInt) = ComplexInt(real + other.real, im + other.im)
       def * (other: ComplexInt) = ComplexInt(
          real * other.real - im * other.im, 
          real * other.im + im * other.real
       )
       def unary_- = ComplexInt(-real, -im)
       def -(other: ComplexInt) = this + -other
    
       override def toString() = (if(real == 0 && im != 0) "" else real.toString) + (im match {
         case 0 => ""
         case 1 if real == 0 => "i"
         case 1 => " + i"
         case n if n < 0 || real == 0 => s"${n}i"
         case n => s"+${n}i"
       })
    }
    
    object ComplexInt {
       val I = ComplexInt(0, 1)
       implicit def fromInt(n: Int) = ComplexInt(n, 0)
    }
    

    现在,你只需要import ComplexInt.I, 然后像println(1 + 2*I + I*3 + 2) 这样的东西会打印3+5i 等等。

    你甚至可以做(1 + 2*I)*(2 + 3*I)(评估为-4+7i)。

    【讨论】:

    • 正如我所说,我刚开始学习 Scala,这是我的第一个任务。我知道我不应该只将解决方案缩小到一种情况,但我认为以某种方式更容易得到答案。这实际上是非常惊人的你所做的。非常感谢。
    • 第一次作业的东西很粗糙
    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多