当我和Scala一起玩时,我无法弄清楚什么。也许我做错了。
我尝试使用Rational Example和Complex Example但我找不到使用R * 3/5和1/2 * R
等操作的方法这是我正在处理的复数示例
class Complex(val real : Int, val img : Int){
def this(real: Int) = this(real, 0)
def *(that : Complex) = {
val realPart = this.real * that.real + -(this.img * that.img)
val imgPart = this.real * that.img + this.img * that.real
new Complex(realPart, imgPart)
}
override def toString = this.real + "+" + this.img + "i"
}
object Complex {
def apply(real : Int, img : Int) = new Complex(real, img)
def apply(real : Int) = new Complex(real)
}
object ComplexNumbers {
def main(args: Array[String]) {
import ComplexConversions._
println(Complex(1,2)) // 1+2i
println(I*2) //0+2i
println(2*I) //0+2i
}
}
我试图创建一个对象
object I{
def apply() = new Complex(0,1)
def *(that : Complex) = {
val realPart = 0 * that.real + -(1 * that.img)
val imgPart = 0 * that.img + 1 * that.real
new Complex(realPart, imgPart)
}
}
但它确实适用于I * 2。但我有2 * I的问题。我怎样才能达到我想要的结果?
答案 0 :(得分:4)
当您拨打" I * 2
"时,scala会查找名为" *
"的方法。在I
的班级上找到它。
当您拨打" 2 * I
"时,scala会查找名为" *
"的方法。在2
的类(Int)上,找不到。
即使Int
是在外部定义的,您也可以通过"隐式转换"在Scala中将此方法添加到Scala中。机制。这在the "implicits" example中有详细介绍,在其他地方也有详细介绍,例如here
尝试将以下代码添加到您的" Complex"对象:
object Complex {
implicit class IntOps(x: Int) {
def *(y: Complex) = y * x
}
}
您还需要将我声明为val,而不是将其声明为对象:
val I = Complex(0, 1)
(或添加隐含的方法,如class Complex { def *(i: I) = ... }
,但这更加丑陋)
(我假设复杂例子,你的意思是this?)
class Complex(val real : Int, val img : Int){
def this(real: Int) = this(real, 0)
def *(that : Complex) = {
val realPart = this.real * that.real + -(this.img * that.img)
val imgPart = this.real * that.img + this.img * that.real
new Complex(realPart, imgPart)
}
override def toString = this.real + "+" + this.img + "i"
}
object Complex {
def apply(real : Int, img : Int) = new Complex(real, img)
def apply(real : Int) = new Complex(real)
val I = Complex(0, 1)
implicit def toComplex(x: Int): Complex = new Complex(x)
}
object ComplexNumbers {
def main(args: Array[String]) {
import Complex._
println(Complex(1,2)) // 1+2i
println(I*2) //0+2i
println(2*I) //0+2i
}
}
答案 1 :(得分:2)
如果您希望能够使用^[a-zA-Z][a-zA-Z0-9.,$;]+$
,则需要为2*I
类添加新的*
覆盖(因为Int
实际上是一种方法班级*
,意思是Int
,2*I
}。
您可以使用隐式类来完成此操作:
2.*(I)