Scala:由int(implicits)预乘实例

时间:2014-03-28 17:24:38

标签: scala implicit-conversion

我试图使用implicits来允许我编写2 * x形式的语句,其中x是X类,需要隐式转换为另一种类型Y.

据我所知,这意味着我还需要将我的Int转换为带有*(:Y)方法的类。 Scala似乎不喜欢它,因为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

1 个答案:

答案 0 :(得分:0)

您可以使用视图绑定来执行此操作:

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

[T <% B]表示T必须隐式转换为B,因此AB都有效。