scala: operation overload and implicit conversion

2019-08-13 20:30发布

问题:

Here is a code sample. Not sure why I am getting error when using multiplication. Should I add implicit conversion to Int ? Sure the answer is simple!! Thanks

    class Fraction(val x:Int, val y:Int)    
    {               
        def X = x
        def Y = y

        implicit def int2Fraction(n: Int) = Fraction(n, 1)
        def *(that: Fraction) : Fraction = new Fraction(that.X * X, that.Y * Y)
    }

    object Fraction {
        def apply(x: Int, y: Int) = new Fraction(x, y)
    }

    val x : Int = 3 
    val result = x * Fraction(4, 5)
    println( result.X )

回答1:

For an implicit conversion to take place, it needs to be in scope. Try taking it outside the class like this:

implicit def int2Fraction(n: Int) = Fraction(n, 1)

class Fraction(val x:Int, val y:Int)
{
    def X = x
    def Y = y


    def *(that: Fraction) : Fraction = new Fraction(that.X * X, that.Y * Y)
}

object Fraction {
    def apply(x: Int, y: Int) = new Fraction(x, y)
}

You can also put it inside the companion object; the compiler searches there automatically.



回答2:

Your implicit conversion function is a member of the Fraction class - so it can't be called without an instance of Fraction. If you move it to the object, it would work as expected:

object Fraction {
    def apply(x: Int, y: Int) = new Fraction(x, y)
    implicit def int2Fraction(n: Int) = Fraction(n, 1)
}


标签: scala