请教scala的隐式转换问题
一个自定义的类Rational,想让这个类跟原生的类型int之间实现隐式转换,实现四则运算
class Rational(n:Int,d:Int) {
private val number = n
private val denom = d
println("create->"+n+"/"+d)
require(d != 0)
def this(n:Int) {
this(n,1)
}
def +(that: Rational): Rational = {
new Rational( number * that.denom + that.number * denom, denom * that.denom )
}
def +(i: Int): Rational = {
new Rational(number + i * denom, denom)
}
implicit def intToRational(x: Int):Rational = {
new Rational(x)
}
}
测试类如下
object Test {
def main(args : Array[String]) {
var x1 = new Rational(1,2)
println(2 + x1)
}
}
执行
println(2 + x1)
这段还是会报错,虽然在自定义类中加了隐式转换函数但还是有问题