2014-03-28 62 views
0

我試圖使用implicits來允許我寫形式爲2 * x的語句,其中x是類X,需要隱式轉換爲另一種類型Y.斯卡拉:int前綴乘積(implicits)

據我所知,這意味着我也需要將我的Int轉換爲帶有*(:Y)方法的類。斯卡拉似乎並不喜歡它,因爲Int已經有一個*方法。除了給我的NewInt類提供一個*(:X)方法以外,還有什麼可以做的嗎?

微創失去作用的例子:

class A 
    class B 
    class C 
    class D { 
    def *(other: B): B = null 
    } 

    implicit def a2b(x: A): B = new B 
    implicit def c2d(x: C): D = new D 

    (new C)*(new A) // This is fine: 
        // C is converted to D, and A is converted to B 
        // and D has a method *(:B) 

    // But... 

    class NewInt(val value: Int){ 
    def *(other: B): B = null 
    } 

    implicit def int2newint(x: Int): NewInt = new NewInt(x) 


    (new NewInt(2))*(new A) // Fine 
    2*(new B)    // Fine 

    // ... here's the problem: 
    2*(new A)    // Error, though if I add 
          // def *(other: A): B = null 
          // to NewInt it is fine 

回答

0

您可以綁定一個視圖做到這一點:

class NewInt(val value: Int){ 
    def *[T <% B](other: T): B = new B 
} 

[T <% B]意味着T必須是隱式轉換爲B,所以既AB工作。

+0

完美。謝謝。 – Lucas